News Feed
Sections




News Archive
feed this:

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
December 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...

0 comments voice your opinion now!
compaing strings auto-converstion in_array strcmp compaing strings auto-converstion in_array strcmp



Community Events





Don't see your event here?
Let us know!


symfony update interview opinion series install release package laravel framework voicesoftheelephpant security library introduction version podcast community language composer tool

All content copyright, 2014 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework