Re: How can an elephant count for nothing?
| From: | Jochem Maas | Date: | Thu, 12 Feb 2009 11:01:26 +0000 |
| Subject: | Re: How can an elephant count for nothing? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-288147@lists.php.net to get a copy of this message | ||
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.
>