on all version of php, i have an problem with switch case statement I can't understand this behaviour =>
$coef = 0;
switch($coef) {
case ($coef >= 0 && $coef <= 2.1):
var_dump( 1);
break;
case ($coef > 2.1 && $coef <= 4.1):
var_dump( 2);
break;
case ($coef > 4.1 && $coef <= 6.1):
var_dump( 3);
break;
case ($coef > 6.1 && $coef <= 8.1):
var_dump( 4);
break;
}
// Return 2 not 1
So the first condition (coef >= 0 && $coef <= 2.1) => return true; The second return false: ($coef > 2.1 && $coef <= 4.1) => return false; The second case always return the result.
To have a normal behaviour we need to write switch case like that :
switch($coef) {
case ($coef === 0):
case ($coef > 0 && $coef <= 2.1):
var_dump( 1);
break;
case ($coef > 2.1 && $coef <= 4.1):
var_dump( 2);
break;
case ($coef > 4.1 && $coef <= 6.1):
var_dump( 3);
break;
case ($coef > 6.1 && $coef <= 8.1):
var_dump( 4);
break;
}
As explained in PHP- Switch case statement with conditional switch, switch always compares the top expression with the result of whatever expression you put into the case.
As explained in the link (and by lukas.j), you need to put true in your top statement, if you want to stop at the first line which evaluates to true.