I am having a problem in php switch case.
When i set $number=0 it should run very first case but here this code returns 10-20K that is in second case.
I checked comparison operators, tested them in if else case they return correct values but here first case do not run on $number=0
Why is this happening ? php consider 0 as false or something wrong in code ?
Link to codepad paste http://codepad.org/2glDh39K
also here is the code
<?php
$number = 0;
switch ($number) {
case ($number <= 10000):
echo "0-10K";
break;
case ($number > 10000 && $number <= 20000):
echo "10-20K";
break;
case ($number > 20000 && $number <= 30000):
echo "20-30K";
break;
case ($number > 30000 && $number <= 40000):
echo "30-40K";
break;
case ($number > 40000 && $number <= 50000):
echo "40-50K";
break;
case ($number > 50000 && $number <= 60000):
echo "50-60K";
break;
case ($number > 60000 && $number <= 70000):
echo "60-70K";
break;
case ($number > 70000 && $number <= 80000):
echo "70-80K";
break;
case ($number > 80000 && $number <= 90000):
echo "80-90K";
break;
case ($number > 90000):
echo "90K+";
break;
default: //default
echo "N/A";
break;
}
?>
You are almost using the switch
in reverse, but not quite. You need to either go fully into reverse by writing switch(true)
:
switch (true) { // IMPORTANT CHANGE HERE!
case ($number <= 10000):
echo "0-10K";
break;
case ($number > 10000 && $number <= 20000):
echo "10-20K";
break;
// etc
}
or otherwise change the whole thing to if
/else
:
if ($number <= 10000) {
echo "0-10K";
else if ($number > 10000 && $number <= 20000) {
echo "10-20K";
}
// etc
Two important notes:
switch
usually looks terribly counter-intuitive the first time you see it. Please do not use it if you don't feel comfortable with it.$number > X
part is made redundant by the fact that the check in the previous conditional ($number <= X
) has already failed. However, it can be argued that keeping the checks makes the code more robust in the face of modification.switch ($number) {
case ($number <= 10000): // check $number == ($number <= 10000)
echo "0-10K";
break;
// you hit the below because `0 == false` is true in php
case ($number > 10000 && $number <= 20000): // check $number == ($number > 10000 && $number <= 20000)
echo "10-20K";
break;
// ...
But you could do it with less code:
function showRange($number) {
if ($number > 90000) {
echo "90K+";
return;
}
echo sprintf("%s-%sK", (int) ($number / 10000) * 10, ((int) ($number / 10000) +1) * 10 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With