# Posted By

mthorn on 08/09/06

# Statistics

Viewed 606 times
Favorited by 0 user(s)

# Compare value _and_ type

/ Published in: PHP
`\$value = '0';     // Here's how PHP works with the normal comparison operator:    if ( \$value )    {        // Since the \$value is 0, PHP interprets it as false. However since         // this is a non-empty string one might expect it to be true.        print "if ( {\$value} )\n";    }     if ( \$value == false )    {        // PHP automatically converts strings to numbers when it things it         // needs to. This can cause problems because you may have wanted to        // check for a boolean, not a string.        print "if ( {\$value} == false )\n";    }     if ( \$value == true )    {        // Since the value is both a string and numericaly 0, this evaluates        // to false. I don't think there is any time when you would want it to        // be true. Thankfully PHP doesn't think so either.        print "if ( {\$value} == true )\n";    }     if ( \$value == 0 )    {        // PHP will convert the value to the type you are comparing before        // comparison. This may not be intented. However this evaluates        // to true.        print "if ( {\$value} == 0 )\n";    }     if ( \$value == '0' )    {        // Since the value matches, this evaluates to true        print "if ( {\$value} == '0' )\n";    }     // Now we try the === operator:    if ( \$value === 0 )    {        // Since the type of the value is not a number, this evaluates to false.        print "if ( {\$value} === 0 )\n";    }     if ( \$value === '0' )    {        // Since type _and_ value matches this evaluates to true.        print "if ( {\$value} === '0' )\n";    }     // Some alternative ways to compare:    if ( (int) \$value === 0 )    {        // Since we typecast to an int, this works.        print "if ( (int) {\$value} === 0 )\n";    }     if ( intval(\$value) === 0 )    {        // Intval takes the integer value of any string        print "if ( intval({\$value}) === 0 )\n";    }     if ( (string) \$value === '0' )    {        print "if ( (string) {\$value} === '0' )\n";    }     /*    The above outputs:      if ( 0 == false )    if ( 0 == 0 )    if ( 0 == '0' )    if ( 0 === '0' )    if ( (int) 0 === 0 )    if ( intval(0) === 0 )    if ( (string) 0 === '0' )    */`