Fairly often, it’s necessary in PHP programming to write your code around the fact that, most of the time, PHP does not distinguish between null
, false
and 0
, although there is, nonetheless, a distinction between all three.
Today I ran into one of the few instances where I was expecting PHP to treat them as equivalent, but it did not.
Often I am working with arrays, and I write conditionals that should only execute if there are elements in the array. Technically the proper check for the status of an array-type variable is the is_array()
function, but most of the time I don’t use that. I may have initialized the array variable or not, but that’s irrelevant to me; what I care about is whether there’s anything in the array, so I just use count()
instead.
These days I’m working on some object-oriented code, and I’ve been writing several “get” methods that return either an array of data or, as I had originally written them, a false
value if no matching data exists.
Fine. But then I applied some of this new OO code to an existing page, and found that one of my count()
-based conditionals was evaluating incorrectly. I checked the variable, whose value was set by one of the object methods, and as anticipated, its value was false
. But strangely, the count()
function was returning 1
rather than 0
when applied to the variable.
I resisted my initial temptation to switch from count()
to is_array()
because I don’t want to have to change every place where I use it. Then I tried changing the “failed” return value of the method from false
to null
and, what do you know, it worked!
So now I’ve gone through all of my various “get” methods and, on failure, they’re returning null
instead of false
.