Feb 28, 2012

PHP :: Advice on using count()

I may be a little late realising this, but a few dozen thousand lines of PHP code in, it's better late than never.

Let's look at example #1 on count() manual
http://php.net/manual/en/function.count.php

$result count(null); // $result == 0
$result count(false); // $result == 1


Does this strike you as a bit odd? Why the hell should count(0) or count(false) be equal to 1?

Well strangely enough, that's how it is. So for example, if you wrote a mysql_query() wrapper where you return false if the query fails and if you expect an array where you check the number of items, you find out that if the query fails, the count will return 1, and you might get some unexpected results.

Keeping computer security in mind, it's best to avoid count() when just checking if some data is returned.

Alternatives are empty() if checks if a variable contains something other than 0, '0', null, false, array() or ''.

OR, in your wrapper functions, if the query fails, just return NULL!



No comments: