I have a problem want to know answer,
Why the following code will print A not default?
$i = 0;
switch ($i) {
case 'A':
echo "i equals A"; //will printed it
break;
case 'B':
echo "i equals B";
break;
case 'C':
echo "i equals C";
break;
default:
echo "i equals other";
}
Anyone can tell me why? I truely don’t understand .
My PHP version is 5.2.17
Theanks.
This comparison is happening:
What happens is that PHP casts the string to an integer. This results in the letter A becoming zero because it doesn’t represent a number.
Hence:
And that case meets the switch, and is therefore executed. Very counter-intuitive, but it’s the way PHP’s type system works, and is unfortunately technically not a bug.
You can solve this by turning
$iinto a string like this:Or by just initializing it as a string if you can: