Isaac Bosca
Isaac Bosca

Reputation: 1648

Switch condition evaluates incorrectly on zero

I was trying a piece of code like this:

$event = 0;

switch ($event) {
    case 'content':
        echo "/content";
        break;
    case 'start':
        echo "/start";
        break;
    default :
        echo "not available";
        break;
}

This code prints /content when is executed, so... 0 (zero, integer, assigned to $event variable) is being evaluated as 'content'. Why?

Upvotes: 2

Views: 49

Answers (3)

Jay
Jay

Reputation: 2686

This is what is actually happening

0 == 'content'

Php tries to cast the string content to an integer. Since content doesnt equal an int, it just defaults to 0.

Resulting in:

0 == 0

Upvotes: 5

djxyz
djxyz

Reputation: 125

That's because the way operators are defined in php when mixing numeric and string variables: When the string has no valid number, it is handled as 0

So:
1+"xxx" => 1+0=1
0=="xxxx =>  0==0=>true
etc..

It's just the way php designed. I don't like it btw

Upvotes: 1

MackProgramsAlot
MackProgramsAlot

Reputation: 593

An implicit conversion from one type to another takes place.

The intval('content') is 0.

Upvotes: 1

Related Questions