Isaac Bosca Isaac Bosca - 1 month ago 21
PHP Question

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?

Jay Jay
Answer

This is what is actually happening

0 == 'content'

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

Resulting in:

0 == 0