NYCPHP Meetup

NYPHP.org

[nycphp-talk] What's going on here? PHP conditional.

David Sklar sklar at sklar.com
Fri Jul 2 11:31:31 EDT 2004


When you compare two scalars of different types, the scalar on the right 
hand side is converted into the type of the scalar on the left hand side.

So in the first comparison, the PHP interpreter turns 'Some String' into 
an integer, following the rules it always does for things like that 
(e.g. if you wrote "print 6 + 'pants';") which is that anything 
numbery-looking at the start of the string is turned into a number and 
the rest is discarded. There are no numbers in 'Some String', so the 
"integer value" of the string is 0.

You can see the same thing at work with something like this:

if (5 == "5 alive") { print "true"; } else { print "false"; }

This prints "true".

David

Brian Kaney wrote:
> Just came across this problem.  Consider the following code:
> 
> <?php
> 
> echo "Equivalent: ";
> if (0 == 'Some String') { echo 'evaluates true'; } else { echo
> 'evaluates false'; }
> 
> echo "\n";
> 
> echo "Equivalent and same type: ";
> if (0 === 'Some String') { echo 'evaluates true'; } else { echo
> 'evaluates false'; }
> 
> ?>
> 
> I get 
> 
> Equivalent: evaluates true
> Equivalent and same type: evaluates false
> 
> 
> 
> Does anyone know why (0 == 'string') evaluates to true?   
> 
> According to the manual, the integer 0 converts to FALSE.  A non-empty
> (or non-zero) string is considered TRUE. I would think if (FALSE ==
> TRUE) should be evaluated as false?
> 
> http://us2.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting




More information about the talk mailing list