[nycphp-talk] Boolean evaluation (PHP vs Java)
paul at devonianfarm.com
paul at devonianfarm.com
Tue Jan 15 11:09:03 EST 2008
I've thought about this for a long time -- and a lot lately since I've been doing mostly Java and ASP.NET to earn my bread in the last six months.
One of the most controversial features of languages such as PHP and Perl is the lax evaluation of boolean values, if you write
print $a ? "True" : "False";
You'll find that many different things evaluate false such as integer and float zero, the empty string, an empty array, a null, etc. Often this is a convenient behavior. For instance, if a function returns an empty array, it's often reasonable to interpret this as a failure, or a false value.
C++ and Java programmers express a lot of anxiety that programs written this way will have lots of problems. My experience is that, coding in PHP, I run into a boolean problem once every couple of weeks. On the other hand, I find that I run into trouble with boolean values much more often when working in Java or C# -- the "false" value is different in every situation, so I need to think about every if() I write and I sometimes make a decision that's wrong in a subtle way -- no wonder why they worry.
In PHP, however, you do end up with a "==" operator that's a little too permissive that thinks that "0"==false and also that "0"="" (empty string). That is a PITB when you're searching for a substring which might be at the start of the string (position 0) or not in the string at all (false). Then you need to use the "===" operator which is a little stricter than people often want -- the language probably could have been better designed.
More information about the talk
mailing list