The case
It turns out that doing some tests I have found a somewhat unusual behavior or that I had not experienced before.
The issue is that the switch function allows consecutive comparisons of the type:
//...
switch ($i) {
case 0:
case 1:
case 'a':
echo "...";
break;
//...
Similar examples appear in the php manual .
The theory is that if the value of $i
is 0
, 1
, or it a
should activate the echo
.
In the case I show:
- The values
0
ora
would return0
. - The values
1
orb
would return1
. - The values
2
orc
would return2
.
But I don't know what reason does not give the expected results with the following example:
class Test {
const A = 0;
const B = 1;
const C = 2;
public function select($value)
{
switch($value) {
case 'a':
case self::A:
return self::A;
break;
case 'b':
case self::B:
return self::B;
break;
case 'c':
case self::C:
return self::C;
break;
default:
return 3;
}
}
}
$test = new Test();
echo $test->select('b');
A working example in a Sandbox .
The problem
All integers return their correct value, but strings always return
0
.
The question
Why do the values with string
not return the corresponding value?
The problem comes from a type conversion, in the documentation we can find the following:
Comparison operators :
What is happening?
First let's see what happens when we force the String
b
to numberIf we see the documentation of Conversion of string to numbers we see the following:
Therefore if we review the
switch
and the results of the example:How to solve it?
For me, the most appropriate way is to force strings in the case, since we could receive numbers as strings and if we force types, these strict comparisons will be false (
string '1'=== int 1 : false
).Example:
The problem may be that, according to the documentation , the switch/case statement works with flexible comparisons. with what this means when comparing strings.
You can see a little more information in this answer
One way to solve it is by "forcing" it to do strict comparisons: