$letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
$x = (1==1 || 2==2);
$y = (3==3 || 4==4);
$z = (5==5);
foreach ($letters as $key => $letter) {
switch ($letter) {
case 'a':
echo "a";
break;
case 'b':
echo "b";
break;
case 'c':
echo "c";
break;
case 'd':
echo "d";
break;
case 'e':
echo "e";
break;
case 'f':
echo "f";
break;
case 'g' && ($z || $y):
echo "g";
break;
case 'h' && ($x):
echo "h";
break;
}
}
I don't know why but at the last two cases the 'g' and 'h' It doesn't work properly and gets a double 'g', The result i expect is
abcdefgh but i keep getting abcdefgg, What am I doing wrong?
Given your code, the g
case will always evaluate to true
:
var_dump('g' && ((5==5) || (3==3 || 4==4))); // true
switch
cases use loose comparison and when $letter
is g
it will be evaluated with true
. Since g
is loosley true
it will execute that case:
var_dump('g' == true); // true
var_dump('g' == false); // false
You probably need this:
case 'g':
if(($z || $y)) { echo "g"; }
break;
It may be intuitive to try and assume switch will spit out boolean values, and you can then append additional boolean logic to your cases. This is wrong, however.
From the PHP docs on switch:
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure.
Each of your cases needs to exactly match the evaluated `$letter$ expression, you cannot have additional boolean expressions and whatever else in the cases.