|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2015-05-01 15:37 UTC] stephane at winnepenninckx dot com
Description:
------------
the case $i < 1 down not occur for $i = 0, the script goes to the default case:
-----------------
0 : Oops
-----------------
If you delete the default case :
-----------------
0 : quite bad!
-----------------
I try with the for loop modified :
for ($i = 10.1; $i >= 0; --$i)
then the case $i<1 occurs :
-----------------
0.1 : really!!
-----------------
It looks like there is a problem with the value 0 when comparing to 1
also in older versions of PHP like 5.5
Test script:
---------------
$sep = PHP_EOL.'-----------------'.PHP_EOL;
echo 'switch demo';
echo $sep;
for ($i = 10; $i >= 0; --$i) {
switch($i) {
case $i < 1 :
$msg = 'really!!';
break;
case $i < 3 :
$msg = 'quite bad!';
break;
case $i < 5 :
$msg = 'pay attention!';
break;
case $i <= 9 :
$msg = 'quite good';
break;
case $i <= 10 :
$msg = 'congrat';
break;
default:
$msg = 'Oops';
break;
}
echo $i . ' : '.$msg.$sep;
}
Expected result:
----------------
when $i = 0 the $msg should be 'really!!' not 'Oops':
-----------------
0 : really!!
-----------------
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 07 17:00:02 2026 UTC |
If they think it's a bug then they must not have as much experience with PHP as they claim. "switch (X) case Y:" is equivalent to "if (X == Y)", so what you've written is like if ($i == ($i < 1)) { } else if ($i == ($i < 3)) { } etc Obviously that's not what you wanted. A switch doesn't make sense for that. It's most useful for dealing with specific values, like if you wanted different behavior for specific values of $i, and not for general conditional logic. Use if instead.I would like that you are right. But I rewrote the switch with 'else if' the way you pretend the switch statement is working and I ended with a different result. for ($i = 10; $i >= 0; --$i){ if ($i == ($i < 1)){ $msg = 'really'; }else if ($i == ($i < 3)) { $msg = 'quite bad'; }else if ($i == ($i < 5)) { $msg = 'pay attention'; }else if ($i == ($i <= 9)){ $msg = 'quite good'; }else if ($i == ($i <= 10)){ $msg = 'congrat'; }else{ $msg == 'Oops'; } echo $i.' '.$msg . $sep; } for $i with value '04 it returns: '0 quite bad' where the switch statement returns '0 : Oops' IMHO this is different.