There’s weakly-typed, then there’s PHP: TRUE == FALSE

programming Add comments

PHP is a weakly-typed language. By that I mean that variables are assigned values without regard to variable type, and implicit type conversion at runtime sorts out any conflicts. PHP will happily let you compare a string and an integer, and will make its best stab at doing what it thought you meant.

Given that one of the most important features 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:


$option = "5";
if ($option == 5) ;

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? Any non-null string evaluates to TRUE, so the first clause evaluates as TRUE.
Integer value 0 evaluates to FALSE, so the second clause evaluates as TRUE.

A string is silently promoted to integer when compared with an integer. If the string is the ASCII representation of a number (eg $a="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 I remember, I’ll throw up some more.

One Response to “There’s weakly-typed, then there’s PHP: TRUE == FALSE”

  1. Simon Says:

    I really don’t know how I would get on with a language that does not check type compatibility at compile time. I find it useful when Pascal fails at compile time if two variables are incompatible. I gives me one less thing to worry about and hopefully makes the code less buggy ?

Leave a Reply

You must be logged in to post a comment.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in