Forum Moderators: coopster

Message Too Old, No Replies

Switch or array for assigning var

or anybody knows a good and safe but different approach

         

mcibor

9:11 pm on Aug 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I was just writing answer to post about switches when it vanished into thin air so I decided to write a new topic.

I want to discuss matter of whever to use switch or not.
Let's say we have a variable that can be either $var "true/ false/ both"
To check that we can use switch:

switch($var) {
case "true": $value = "It was true!"; break;
case "false": $value = "It wasn't true."; break;
case "both": $value = "It was almost true, but not quite"; break;
default : die("Sorry wrong choice. Try again.");

Or we can use array:
$values = array("true"=>"It was true!", "false"=>"It wasn't true.", "both"=>"It was almost true, but not quite");
if(!($value = $values[$var])) die("Sorry wrong choice. Try again.");

I wonder what are the pros and cons of using either method.
Best regards
Michal Cibor

PS. I think it's a good alternative to using switch in this case certainly!

coopster

11:21 pm on Aug 17, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



There is always more than one way to do it. The switch control structure comes in handy when you have more than one thing to do. In your example, you are simply checking for a value in the array. But, what if you wanted to set other values and/or do some more processing besides that? That's when the switch may be easier to work with and format your logic in a manner that is easy to read.
switch($var) { 
case "true":
$value = "It was true!";
$another_value = "Yes";
break;
case "false":
$value = "It wasn't true.";
header("Location: $url");
exit;
break;
case "both":
$value = "It was almost true, but not quite";
print "You can't have it both ways!";
break;
default :
die("Sorry wrong choice. Try again.");
}