having the integer 0 as switch parameter will take the first result "foo":
$data=0; // $data is usually coming from somewhere else, set to 0 here to show the problem
switch ($data) :
case "anything":
echo "foo";
break;
case 0:
echo "zero";
break;
default:
echo "bar";
endswitch;
How do I change this, so the switch will write "zero" as expected?
Switch/case statement uses "loose-comparison" (i.e. ==
. in this case, 0
also means false
and 1
also means true
. (http://www.php.net/manual/en/types.comparisons.php#types.comparisions-loose)
To avoid this problem, two solutions:
1) As suggested by @zzlalani, add quotes.
case '0': ...
2) Explicitly cast the switch statement to force a strict comparison (===
)
switch((string)($data)) { ... }
The switch/case statement uses loose comparison, and, like it or not, 0 == "anything"
is true
:
Comparison Operators
[...] If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. [...]
var_dump(0 == "a"); // 0 == 0 -> true
One solution is to change all case statements to string, and do a string comparison:
$data = 0;
switch ((string) $data): ## <- changed this
case "anything":
echo "foo";
break;
case "0": ## <- and this
echo "zero";
break;
default:
echo "bar";
endswitch;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With