Jochem Maas wrote:
because intval("elephant") == 0;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. intval will convert the string into integer , Strings will most likely return 0 although this depends on the leftmost characters of the string. --
惠 新宸 xinchen.hui | SYS | (+8610)82602112-7974 | :laruence |