[nycphp-talk] comparison with zero
Chris Shiflett
shiflett at php.net
Fri Jul 21 11:19:31 EDT 2006
Scott Mattocks wrote:
> When a string is converted to a number, it will be converted
> to zero unless it begins with a number.
I like to think of this is a side-effect of the way PHP determines the
numeric value rather than a special case. The string is scanned from
left to right, and as long as the characters can possibly represent a
numeric value, they are considered to be part of it.
All of these evaluate to TRUE:
var_dump(10 == '10');
var_dump(10 == '010');
var_dump(10 == '10ronaldinho');
var_dump(10 == '10e');
var_dump(10 == '+10e');
var_dump(10 == '10abc20');
E and + are the only non-digit characters that can be interpreted as
representing a numeric value, as far as I'm aware, and it depends on
where they're encountered. (I think + needs to be the first character,
in which case it's superfluous anyway, and E needs to be followed by a
digit.)
These evaluate to FALSE:
var_dump(10 == '10e2');
var_dump(10 == '10E2');
If you're like me, this is surprising. You're probably thinking that the
strings on the right are being converted to integers, because that's
what they're being compared to. Nope, because these evaluate to TRUE:
var_dump(10 == (int)'10e2');
var_dump(10 == (int)'10E2');
These evaluate to FALSE:
var_dump(10 == (float)'10e2');
var_dump(10 == (float)'10E2');
So, I would consider this to be the special case, not strings that don't
begin with a digit.
> A non-empty string that is converted to a boolean will be
> converted to TRUE.
Just so no one is mislead, I think Scott means empty() as in the
function, not all strings that are not the empty string. For example:
$true = '0';
if (!$true) {
echo "The string '0' is not TRUE.";
}
Hope that helps.
Chris
--
Chris Shiflett
Principal, OmniTI
http://omniti.com/
More information about the talk
mailing list