Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is php switch statement bug?

Tags:

php

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.

like image 776
Jasper Avatar asked Dec 06 '22 18:12

Jasper


1 Answers

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';
like image 180
BoltClock Avatar answered Dec 10 '22 13:12

BoltClock