Re: How can an elephant count for nothing?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



惠新宸 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.
>>> For instance 
>>>
>>> $string =  'elephant';
>>> If($string == 0) returns true;
>>> If($string != 0) returns false;
>>> If($string === 0) returns false; 
>>>
>>> I know that in this case I should use 'If($string == '')', but I still manage to forget.
>>> Can anyone explain clearly why comparing a string with zero gives this apparently
>>> anomalous result?
>>>     
>>
>> it's called auto-casting (or auto-typecasting) and it's 'by design'
>> ... welcome to the world of dynamic typing.
>>
>> try this to see it working:
>>
>> php -r '
>> var_dump((integer)"elephant");
>> var_dump((float)"elephant");
>> var_dump((bool)"elephant");
>> var_dump((array)"elephant");
>> var_dump((object)"elephant");
>> var_dump((bool)(integer)"elephant");
>> '
>>
>> 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.
> 
> -- 
> 
> Baidu惠新宸 xinchen.hui* | * SYS *| * (+8610)82602112-7974 *|* Hi:laruence
> 
'2 elephants' != 0

-- 
Thanks!
-Shawn
http://www.spidean.com

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


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux