DAB
DAB

Reputation: 1343

Why does PHP recognize int 0 as the first case in a switch statement?

Why does the following code trigger the first case, instead of the one that actually matches.

switch (0) {
    case 'test':
        echo 1;
        break;
    case 0:
        echo 2;
}

result: 1

It seems to be something with 0. If i try switch(1) I get nothing, and switch(2) will trigger case 0 which is expected.

This is in php 7 on both mac and debian.

Upvotes: 1

Views: 42

Answers (1)

colburton
colburton

Reputation: 4715

You are comparing an integer to a string. This can't be done, so PHP does an implicit type cast.

PHP picks the cast to integer and converts 'test'.

And (int)'test' is 0. Therefore the first statement matches.

This could get even weirder:

switch (1) {
  case '1test':
    // would also match
  break;
}

Upvotes: 2

Related Questions