0
Is it a bug in switch statement?
Why do we get âit is tenâ instead of âno matchâ when for $z assigned value 0? With other values except 10 it prints âno matchâ. $z = 0; switch($z) { case ($z === 10): echo "<br> it is ten"; break; default: echo "no match"; break; }
3 Answers
+ 2
Each case is compared for equality with the switch operand.
switch($a) {
case $b: // passes if $a == $b
}
So your question,
switch($z) {
case ($z === 10):
// passes if $z === ($z === 10)
}
Let me break that down
$z == ($z === 10)
0 == (0 === 10)
0 == 0
1 // passes
The correct program should be
$z = 0;
switch($z) {
case 10:
echo "<br> it is ten";
break;
default:
echo "no match";
break;
}
Which can be shortened to
$z = 0;
echo($z === 10 ? "<br> it is ten" : "no match");
+ 1
Thank you for your answer, now I understand why it shows me this result. So in this case it is better to use elseif to avoid an incorrect result?
+ 1
Vadims Lukjanskis You can just write case 10 instead of case ($z === 10)