Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Greg Beaver's Blog:
comparing strings in PHP with the == operator
Dec 16, 2005 @ 07:11:30

On Greg Beaver's blog today, there's his look at string comparison with the "equals equals" (==) operator in PHP and some issues he found around it.

Recently, an obscure detail in the way PHP processes strings came to my attention in the form of an endless loop occasionally found in phpDocumentor's parsing of a file.

This is processed by code that checks for simple lists (like 1. blah 2. blah, or - blah - blah, etc.). However, an innocent call to in_array($x, array('1.', '0.')) had surprising and unexpected results: our friendly PHP determined that '01' was in the array('1.', '0.')!! This is of course patently false, and made little to no sense until I realized that unlike my previous understanding (when comparing an integer to a string, the string is converted to an integer), PHP actually converts all numeric-like strings into integers when comparing them.

To help avoid these kinds of situations repeating themselves, he makes a few suggestions when comparing your values: "use === instead of ==", "use the third parameter in in_array, set to true", and "use strcmp() or one of its cousins". In his opinion, though, this kind of auto-conversion is a bit dangerous - bit it's all about perspective...

tagged: compaing strings auto-converstion in_array strcmp compaing strings auto-converstion in_array strcmp