Can this be done? [PHP]

Associate
Joined
26 Jun 2003
Posts
1,140
Location
North West
On my pages i usually do a big if/else/switch to decide which function to call

PHP:
if ($_GET['action'] == 'whatever')
  doThis();
else if ($_GET['action'] == 'bob')
  doThis2();

Is it possible to do sumthing like this:

$action['whatever'] = doThis();
$action['bob'] = doThis2();

Then how would I call the appropiate function to be called depending on the value of $_GET['action']?

Is it possible?

Is there another way to do what I want with less/tidy/efficient code?

Thx
 
Associate
OP
Joined
26 Jun 2003
Posts
1,140
Location
North West
Ok i found a way, however if $_GET['action'] isnt set or is set to a value that is not in the array then i recieve an error. How could I get around this?

Again this may not be the best way to do it so if anyone has another method, please share. :D

PHP:
function login() { } 
function logout() { }
function registrationForm() { }

$_action['login']    = 'login';
$_action['logout']   = 'logout';
$_action['register'] = 'registrationForm';

call_user_func($_action[$_GET['action']]);

Thx
 
Associate
OP
Joined
26 Jun 2003
Posts
1,140
Location
North West
Ill have a look at the in_array() and isset() stuff.

Id know i could do it with if/else/switches but I find the code quite ugly and hard to organise etc, which is why I thought the array idea would be good.

---

The following method seems to work, can anyone spot a time where it will fail?

PHP:
$_action = array (
	''         => 'login',
	'login'    => 'login',	
	'logout'   => 'logout',	
	'register' => 'registerForm'
);	

if (array_key_exists($_GET['action'], $_action))
	call_user_func($_action[$_GET['action']]);
else
	header("Location: index.php");

Thx
 
Last edited:
Back
Top Bottom