You choose between [tt]
if[/tt] and [tt]
switch[/tt] depending on the shape and form of your needs. I can think of examples where [tt]
if[/tt] is absolutely preferred over [tt]
switch[/tt]
and vice versa.
However, here's two somewhat important differences to consider:
First difference - Quote from "SAMs Teach Yourself PHP in 24 hrs, 2nd. edition"
The result of an expression evaluated as part of an [tt]if[/tt] statement is read as either true or false.
The expression of a [tt]switch[/tt] statement yields a result that is tested against any number of values.
Second difference - Quote from php.net's online manual
In a [tt]switch[/tt] statement, the condition is evaluated only once and the result is compared to each case statement. In an [tt]elseif[/tt] statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a [tt]switch[/tt] may be faster.
I don't know how to compare [tt]break;[/tt] and [tt]goto[/tt]. Doesn't make sense to me -different languages; different purpose §;O)
Remembering the [tt]break;[/tt] is a given when you use the [tt]
switch[/tt] statement. I realize that there can be a loophole if you forget it, so it is (as always) important to test you code thoroughly.
Having said that, you can in fact leave out the [tt]break;[/tt] to serve special needs.
Consider this example
Code:
function switchStatement($country) {
switch($country) {
case "Ireland" :
case "US" :
case "Australia" :
case "New Zealand" :
case "Canada" :
case "UK" :
return "Hello!";
break;
case "Belgium" :
case "Morocco" :
case "Ivory Coast" :
case "France" :
return "Bon jour!";
break;
case "Denmark" :
return "Hej!";
break;
default :
return "How do I greet you?";
}
}
Which,
could look like this using an [tt]
if/elseif/else[/tt] construction instead:
Code:
function ifStatement($country) {
if($country=="Ireland")
return "Hello!";
elseif($country=="US")
return "Hello!";
elseif($country=="Australia")
return "Hello!";
elseif($country=="New Zealand")
return "Hello!";
elseif($country=="Canada")
return "Hello!";
elseif($country=="UK")
return "Hello!";
elseif($country=="Belgium")
return "Bon jour!";
elseif($country=="Morocco")
return "Bon jour!";
elseif($country=="Ivory Coast")
return "Bon jour!";
elseif($country=="France")
return "Bon jour!";
elseif($country=="Denmark")
return "Hej!";
else
return "How do I greet you?";
}
Maybe not the brightest and most useful example, but it serves this purpose well, I recon. This is also an example how a [tt]
switch[/tt] statement can give (in this case & in humble opinion) better overview than the [tt]
if[/tt] statement. Surely you can code it differently, but I think you get the general idea.
Finally, combining the two will sometimes make sense too.
Best Regards
Jakob