Fun with counting in PHP

PHP’s loose typing can throw up some amusing bugs, take using scalars with the count() function. The function isn’t designed for scalars sure, but it doesn’t complain about them and often PHP makes use of global functions like count() rather than the more object orientated $i.count style, creating a nasty little minefield (one of many) for those unfamiliar with PHP’s peculiarities regarding proper objects vs. native types.

So the following looks valid enough:

$i = 5;
if (count($i) > 0) print "true";

But the code is bugged and whilst true will be printed as expected (maybe satisfying the programmer’s initial testing), guess what happens here:

$i = 0;
if (count($i) > 0) print "true";

We get an output of true !?#!??

What happens is the count() function evaluates one scalar value (the 0 integer) and so returns an integer of 1, which is greater than 0.

The following will print true:

$i = false;
if (count($i) > 0) print "true";

Whilst the following will not print anything:

$i = null;
if (count($i) > 0) print "true";

So remember, unless you want weirdness, only use the count() with arrays and objects implementing a Countable interface.

Advertisements

Leave a Reply