Reputation: 98
Could someone please explain what's going on here? Here's the code:
$num = 0;
switch($num){
case ($num==0):
echo $num , " is ZERO";
break;
case ($num>0):
echo $num , " is POSITIVE";
break;
default:echo $num , " is NEGATIVE";
}
The above outputs 0 is POSITIVE
if($num==0){
print ($num." is ZERO");
}
elseif($num>0){
echo $num , " is POSITIVE";
}
else{
echo $num , " is NEGATIVE";
}
This works as expected - 0 is ZERO. If I replace case($num==0) with case(0) the output is OK.
Why does the case($num==0) fail? Someone told me the issue with evaluating multiple expressions in the case statements, but it seems fine syntactically.
Upvotes: 0
Views: 118
Reputation: 23719
The logical structure of switch operator is this:
switch($x):
case val1:
action 1;
break;
case val2:
action 2;
break;
default:
not val1 and val2;
switch compares $x with one of the values or gives default
branch in case nothing matches. So, you can't write:
case ($num > 0):
or
case ($num == 0 ):
In your case it gives POSITIVE, because php first evaluates the expressions inside cases, and we get the following in the output:
Is $num == 0 ?: yes => 1
Is $num > 0 ?: no => 0
And the real switch php evaluates is this:
$num = 0;
switch($num){
case 1:
echo $num , " is ZERO";
break;
case 0:
echo $num , " is POSITIVE";
break;
default:
echo $num , " is NEGATIVE";
}
Output is: POSITIVE.
Upvotes: 1
Reputation: 521995
switch
compares everything in the switch (...)
expression to each case:
switch ($num) {
case 0 :
...
case 1 :
...
...
}
You don't write case $num == 0
, as that's equivalent to if ($num == 0 == $num)
.
If at all, you'd have to do:
switch (true) {
case $num == 0 :
...
case $num > 0 :
...
...
}
But there are people who frown upon that.
Upvotes: 1