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:
0 == 'A'
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:
0 == 0
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 $i
into a string like this:
switch ((string) $i) {
Or by just initializing it as a string if you can:
$i = '0';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With