Why is the below code printing out both "yes" and! "no" ?
Only if I add ‘break;’ to the TRUE case, it only prints out "yes" , but that shouldnt change the fact that the case FALSE, is not going to run, $arr is always an array.
Am I doing something wrong?
$arr=[1,2];
switch (is_array($arr)) {
case TRUE:
print "yes";
//break;
case FALSE:
print "no";
}
2
Answers
Well… the
switch
statement requires abreak
after each case, since by default it’ll will try to execute the nextcase
; as said on w3school :Now about the expected return value, the condition will return a boolean indeed, but not in the
ALPHA
format, but rather in aNUMERIC boolean
, by that I mean it’ll return1
if verified and nothing if not, as w3school saysSo you might want to adjust your expected output from
TRUE
to1
andFALSE
to ”The reason why the code is printing out both "yes" and "no" is because in a switch statement in PHP, if there is no break statement at the end of each case block, the execution will "fall through" to the next case block, regardless of whether the condition, in that case, the block is true or false.
In this case, since $arr is an array, the condition in the first case block (TRUE) is true, and "yes" is printed. However, since there is no break statement, the execution falls through to the next case block, which prints out "no" because it is the default case.
If you add the break statement to the end of the first case block, the execution will stop after "yes" is printed, and "no" will not be printed. Here’s the updated code:
This will only print out "yes" since the execution will stop after the first case block.