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.   

Advertisements

3 thoughts on “A simple ‘Gotcha’ in PHP

  1. Pingback: Comparator Operators is the new black » Blog Archive » Quick Roundup

  2. Pingback: Comparator Operators is the new black » Blog Archive » What others have been saying about comparator operator

  3. Pingback: PHP ‘Good’ Practices « Glorified Geek

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s