On Thu, 12 Feb 2009 23:47:31 +0800, huixinc...@baidu.com (???) wrote:

>Jochem Maas wrote:
>> Clancy schreef:
>>> While PHP has a lot of nice features, it also has some traps which I am 
>>> forever falling
>>> into. One which I find particularly hard to understand is how mixed mode 
>>> comparisons work.
>> you can avoid auto-casting if needed, in a variety of ways:
>> php -r '
>> $foo = "elephant";
>> if (!empty($foo))
>>      echo "$foo found!\n";
>> if (strlen($foo))
>>      echo "$foo found!\n";
>> if (is_string($foo) && strlen($foo))
>>      echo "$foo found!\n";
>> if ($foo !== "")
>>      echo "$foo found!\n";
>> if ($foo === "elephant")
>>      echo "$foo found!\n";
>> '
>> those last 2 show how to use 'type-checked' equality
>> testing.

>because  intval("elephant") == 0;
>intval will convert the string into integer , Strings will most likely 
>return 0 although this depends on the leftmost characters of the string.

This seems to be the nearest to the correct answer. In fact it appears that if 
you compare
a string with an integer the effective value of the string is the value of the 
character(s), if it/they  are integers, or zero.

        elephant == 0; true
        an elephant == 0; true
        1 elephant == 0; false
        0 elephants == 0; true
        a herd of elephants == 0; true
        7 elephants == 7; true
        9999 elephants == 9999; true

The next question is ' how is the order of conversion determined?' I thought it 
might have
converted the second element to the same type as the first element, so I 
reversed the
comparison, but I got exactly the same results, so perhaps it converts from the 
complex type to the simpler type.

Clearly the lesson is to be learnt is not to compare disparate types, unless 
you really
have to.

One situation where this is unavoidable is if you are searching an arbitrary 
set of
strings for a given word.  In this case it is essential to do the exact 
comparison, or you
will get erroneous results.

Thank you all for your suggestions.

PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to