Re: How can an elephant count for nothing?
| From: | Clancy | Date: | Fri, 13 Feb 2009 06:09:00 +0000 |
| Subject: | Re: How can an elephant count for nothing? | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-288203@lists.php.net to get a copy of this message | ||
On Thu, 12 Feb 2009 23:47:31 +0800, huixinchen@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 first
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 more
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.