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; }

19th Nov 2020, 11:13 AM
Vadims Lukjanskis
Vadims Lukjanskis - avatar
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");
19th Nov 2020, 12:21 PM
Ore
Ore - avatar
+ 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?
19th Nov 2020, 12:37 PM
Vadims Lukjanskis
Vadims Lukjanskis - avatar
+ 1
Vadims Lukjanskis You can just write case 10 instead of case ($z === 10)
19th Nov 2020, 12:59 PM
Ore
Ore - avatar