Re: Zero is equal to any string?

From: Date: Sun, 03 Sep 2000 06:41:42 +0000
Subject: Re: Zero is equal to any string?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-14967@lists.php.net to get a copy of this message
Simon Garner writes: > Hi, > > I encountered some rather baffling behaviour today while working on a page, > and eventually narrowed the problem down to the following: > > <? > if (0 == "some string") > { > echo "They're equal!"; > } > ?> > > This will echo "They're equal!", which makes no sense to me. Why should 0 be > equal to any string? 0 should surely be equal only to the empty string and > the boolean value false. > > Note that (1 == "some string") returns false, and so does (0 === "some > string") as expected. I've tested the (0 == "some string") under 4.0.2, > 4.0.1pl2 and 3.0.16 always with the same results. > > Is this a bug or a "feature" of the language? > > > > Cheers, > > Simon Garner It's perfectly normal, given the way that PHP converts strings into integers (and the way it compares): read the section on String Conversion in the manual: http://www.php.net/manual/language.types.string.php#language.types.string.conversion Anyway, the upshot is that in the test above, the string is being converted into an integer for the comparison. Since a string converted into an integer is evaluated as equivalent of all the digit characters of the string before the first non-digit character, and since there are no digits before the first non-digit, the resulting int is '0'. This probably wasn't the clearest explanation, but check out the manual section I just referenced, and the section on Type Juggling (http://www.php.net/manual/language.types.type-juggling.php) for more information. Try some of the examples; it should make sense shortly. :) BTW, '0 === "some string"' returns false because '===' means 'equalivalent and identical types', whereas '==' means 'evaluates to the same value as'. Cheers, Torben -- +----------------------------------------------------------------+ |Torben Wilson <torben@php.net> Netmill iTech| |http://www.coastnet.com/~torben http://www.netmill.fi| |Ph: 1 250 383-9735 torben@netmill.fi| +----------------------------------------------------------------+

« previous php.general (#14967) next »