Note

Written 2008. Still correct. I don’t think there’s anything wrong with implicit type conversion, I just think it has corners.

Stupid PHP Tricks: (true == false)

PHP is a weakly-typed language. By that I mean that variables are assigned values without regard to variable type, and implicit conversion at runtime sorts out any conflicts. PHP will happily let you compare a string and an integer, and if the string contains something unexpected, well, you should have paid more attention to data validation.

Given that the most important feature of PHP is the shallow learning curve, and that it is deployed in an environment where everything is a string, it’s (just) possible to argue that this was a good design decision. It allows you to do things like this:

$n = "5";
echo 3 + $n;

without getting into lots of tiresome explicit conversion. But the implicit rules are sometimes a little too clever for their own good, and throw up oddities like this:

$a = 'string';
$b = 0;
 
if ( $a == true && $b == false && $a == $b )
{
    echo ( 'universe broken' );
}

What’s going on here? Lets look at these three clauses in detail:

  • ( 'string' == true ) because any non-null string evaluates to true when compared with a boolean
  • ( 0 == false ) because the integer 0 undergoes implicit conversion to boolean and evaluates to false
  • Finally, ( 'string' == 0 ) because a string is silently promoted to integer when compared with an integer. If the string is the ASCII representation of a number (eg "123"), it is assigned that value. If it doesn’t contain a number, it is assigned the value 0. So our third clause evaluates as true. Oops…

I routinely use the triple-equals operator (identical) instead of the double-equals operator (equality) now, but it feels and looks like a hack to avoid someone else’s bad design decision biting me. PHP is chock-full of these little oddities.

If you want all the gory details, the type comparison tables are tucked deep inside the PHP Manual.

Update: This post over at Hacker News contains an excellent one-line summary of what I was getting at.