Is there anyway to make it so that the following code still uses a switch and returns b
not a
? Thanks!
$var = 0;
switch($var) {
Switch statement in php does loose comparisons only (==) see http://www.php.net/manual/en/control-structures.switch.php
Use if/elseif/else if you need strict comparisons.
Presumably you are switching on the variable and expecting integers. Why not simply check the integer status of the variable beforehand using is_int($val)
?
Extrapolating from your example code, I guess you have a bunch of regular cases and one special case (here, null
).
The simplest I can figure out is to handle this case before the switch:
if ($value === null) {
return 'null';
}
switch ($value) {
case 0:
return 'zero';
case 1:
return 'one';
case 2:
return 'two';
}
Maybe also add a comment to remember null
would unexpectedly match the 0
case (also the contrary, 0
would match a null
case).