Re: The Context of 0
| From: | Carlton Whitehead | Date: | Tue, 02 Oct 2007 18:06:11 +0000 |
| Subject: | Re: The Context of 0 | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-262651@lists.php.net to get a copy of this message | ||
This should be a lesson about how important it is to keep in mind the *type* of data when writing
comparisons, even in a dynamic/weakly-typed language like PHP.
For example, consider this test case:
<?php
if (0 == false) { echo 'PHP thinks the integer 0 is equal to boolean false, even though they
are a different type'; }
if (0 === false) { echo 'PHP thinks the integer 0 is equal to boolean false and is of the same
type'; }
?>
The == operator performs a very loose comparison of "equality" between the supplied
values, converting the types before performing the comparison. When false is converted to an
integer, it converts as 0, which happens to be the same as 0, therefore the code block executes.
The === operator performs a stricter comparison of equality between the supplied values, taking into
account the type. Because an integer and a boolean are being compared, it will always evaluate as
false. The code in the second if-statement will never be executed because of this.
Also keep in mind the != and !== operators differ from each other in much the same way as == and ===
differ.
Refer to http://www.php.net/manual/en/language.operators.comparison.php
for more details about this.
Regards,
Carlton Whitehead
----- Original Message -----
From: "Jay Blanchard" <jblanchard@pocket.com>
To: php-general@lists.php.net
Sent: Tuesday, October 2, 2007 1:14:42 PM (GMT-0500) America/New_York
Subject: [PHP] The Context of 0
[small rant]
This morning's thread on strpos() brings up an interesting point, zero
has a context.
In certain cases 0 is the equivalent of FALSE and in other cases a 0 is
just a 0. In the context of strpos() 0 indicates that the needle is in
the first position of the haystack. If the needle is not found in the
haystack a Boolean FALSE is returned. In this case 0 is not the
equivalent of FALSE.
There are other cases, most of them specific to strings, in which 0 is
not the equivalent of FALSE. Newbies to PHP or certain functions will no
doubt encounter these cases at some point.
Exercise care when using 0 to determine if something is FALSE and
understand that 0 has context.
[/small rant]
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php