[ Content | View menu ]

PHP Insanity II

Mark Mzyk | December 21, 2007

I have a feeling this might become a regular series.

Today’s insanity is brought to you by the function intval.  Let’s pull a quote straight from the php.net intval page:

Intval returns:

The integer value of var on success, or 0 on failure. Empty arrays and objects return 0, non-empty arrays and objects return 1.

What are the practical implications of this.  Let’s try this:


What is the value returned?  0.  In fact, anything other than an integer will return 0 (with the exception of a few strings – see part I of this series).  But wait, I know what you’re thinking: 0 is in fact, an integer.

Yes, that means that on failure, intval will return a valid integer!

If you notice the second part of the quote, intval can also return a valid integer of one in some cases.  I’m just going to pretend I didn’t read that for now, as that doesn’t make the situation any better.

What then are the implications of this for me, the programmer?  In short, I can’t trust intval, since an expected and valid output is also the failure code.  This is an incredibly poor design decision.  I now have to code around intval by using functions such as is_numeric in conjunction with intval to ensure that I can properly interpret the returned value.

Perhaps you could argue that I should understand my program well enough that I should know the inputs going into intval, but that isn’t always a realistic scenario.  I could be working on only a small piece of a much larger system, and I only know the transformations I need to perform on a given input, not necessarily what the input itself will be.

Also, what if I don’t know about this behavior of intval, which is very likely the case for many programmers?  The results of my program could be strange indeed.

PHP’s inconsistencies and poor design choices force me not to trust the language.  Whenever I receive unexpected output, it is becoming a tendency for me to first question the language and not my own coding, when the situation should be reversed.  Also, by being forced to check in on the language, my productivity drops.  This is not a situation I want to be in.

In the future, given a choice of languages to use on a project, I will not be opting for PHP.  I don’t care how much PHP improves, experiences like these will keep me away.  Programming takes an implicit trust between programmer and language, and with PHP that trust doesn’t exist.  If PHP doesn’t quickly rectify the situation, it will slow fade into oblivion, and quite frankly, that will suit me just fine.