I've recently come across a very strange behaviour in the PHP switch case when dealing with the string '-0'
.
/*
The code below echos:
'How did that happen? "0" and "0" are two different strings.'
*/
$myString = '-0';
switch($myString) {
case '0':
echo 'How did that happen? "-0" and "0" are two different strings.';
break;
case '-0':
echo 'This is normal.';
break;
}
Oddly, the switch statement above executes case '0'.
Going back to the code above, it seems that if you change the order of the cases and place case '-0'
before case '0'
, it seems to work fine and execute case '-0' as it should.
Why is that? Is there reasoning behind this strange behaviour?
While writing this question, I found out that PHP does NOT use strict equality for validating switch cases (unlike other scripting languages such as JavaScript).
Therefore, case '0'
executes if '0' == '-0'
, and since that is true, runs that instead (because it checked for that case first).
If case '-0'
was placed first, it checks for that first, therefore executing that case, and since both cases are valid / TRUE
, it runs the first case in the switch statement.