A simple ‘Gotcha’ in PHP

Can you tell the output of the following code?


$a = 0;
$b = "test"
echo ($a != $b) ? "$ a Not Equals $b" : "$a Equals $b";

If you think the output is “0 not equals test” you would be wrong. Its the other one. Have a look at the PHP type comparison table and you’ll know why.

The ‘==’ is called loose comparison operator. It will automatically type cast one of its two operands and perform comparison. This sounds convenient when you try to compare 0 with ‘0′ without the need of explicit type casting. But 0 equals ‘test’? This will scare off a programmer who is new to PHP.

This is why use of ‘===’ is recommended by PHP Gurus instead of ‘==’. The ‘===’ returns true when the operands are identical i.e. the have the same value and they are the same type. The PHP online manual has a helpful section on this topic.

And by the way, please don’t hate PHP for this. Because PHP is not alone. JavaScript thinks 0 and ‘ ‘ are the same. And C treats any non zero value as boolean true. Only good programming practice can help you avoid these programming potholes.   

3 Responses to “A simple ‘Gotcha’ in PHP”

  1. [...] http://rubayeet.wordpress.com/2008/04/29/a-simple-php-gotcha/The ‘==’ is called loose comparison operator. It will automatically type cast one of its two operands and perform comparison. This sounds convenient when you try to compare 0 with ‘0′ without the need of explicit type casting. … [...]

  2. [...] http://rubayeet.wordpress.com/2008/04/29/a-simple-php-gotcha/The ‘==’ is called loose comparison operator. It will automatically type cast one of its two operands and perform comparison. This sounds convenient when you try to compare 0 with ‘0′ without the need of explicit type casting. … [...]

  3. [...] 1. Use ‘===’ instead of ‘==’ for equality. ‘===’ compares both the types and values of its operands, unlike ‘==’ which only compares values. (That is why 0 == ‘0′ returns true in PHP, but what about 0 == ‘test’ ? Take a look.) [...]

Leave a Reply