Reputation: 2783
$bytes = 0;
switch($bytes){
case $bytes == 0:
echo 'Equal to 0.';
break;
case $bytes < 0:
echo 'Less than 0.';
break;
}
This outputs "Less than 0."
Why?
Upvotes: 3
Views: 2874
Reputation: 3914
An old question, but there's another way of using switch :) I found it on SitePoint!
switch (true) {
case $bytes == 0: // result of this expression must be boolean
echo 'Equal to 0.';
break;
case $bytes < 0: // result also must be boolean
echo 'Less than 0.';
break;
default:
}
Explanation: if true == ($bytes == 0)
or if true == ($bytes > 0)
or default:
You can use switch (false) {}
if you have many falsy results instead of x != y
Upvotes: 2
Reputation: 227270
switch
statements don't work like that. When checking each case
, the value is compared to the case
value (using ==
).
So, PHP is doing:
$bytes == ($bytes == 0)
? Which is: $bytes == (true)
. This is false
, so it's skipped.$bytes == ($bytes < 0)
? Which is: $bytes == (false)
. This is true
, so it runs that block.You need to use an if/else
here.
$bytes = 0;
if($bytes == 0){
echo 'Equal to 0.';
}
elseif($bytes < 0){
echo 'Less than 0.';
}
Upvotes: 8
Reputation: 1534
You cannot use operators in your switch statements. It actually should be:
$bytes = 0;
switch($bytes){
case 0:
echo 'Equal to 0.';
break;
default:
echo 'Something else';
break;
}
Have a look at the full documentation: http://www.php.net/manual/en/control-structures.switch.php
Why does your sample result in 'less than zero'? Easy question: ($bytes < 0) evaluates to false, since it isn't. False is equivalent to 0 so it matches $bytes and falls into that case.
If you need to match certain ranges you are bound to use if-else-constructs.
Upvotes: 0