I’ve taken a look at the documentation for switch on php.net and as best as I can tell it checks a equality comparison between the variable in the switch and the case. However, the following code seems to work properly for all possible values (int, null, array, other):
$x = array('one','two');
switch ($x) {
case null:
echo "is null!";
break;
case is_int($x):
echo "is int";
break;
case is_array($x):
echo "is array!";
break;
default:
echo "something else!";
break;
}
From what I read, it should be comparing is_int($a) [true] to $x [an array, which evaluates to true] and giving an incorrect result.
My question is … why is this actually working?
is_int($x)does not evaluate to true if x is an array. This works becausearray('one', 'two')is considered true, andis_array()will evaluate to true. This means it does not matchnulloris_int($x)(the latter comes out to false). If it’s an int, then the opposite is true andis_array($x)becomes false. If$xisnull, it evaluates tofalse, as doesnullin the switch. Thenullcase will be executed for any circumstance where$xis false (try it withfalse,array(),0, and others).