array() == false
Yesterday I’ve noticed that too many queries are sent to the database server, even though the result should be cached in memcache. After digging into the source and testing, I’ve discovered something like this:
-
$results = $memcache->get('key');
-
if (!$results)
-
{
-
$results = $this->fetchFromDb();
-
$memcache->set('key', $results);
-
}
-
return $results;
The fetchFromDb() method returned an empty array, which was stored in memcache. But, as it turns out, the bug was in checking of $results. An empty array evaluates to false when checking for true/false. I knew that already, but I missed this one.
So, the script issued a query, even though it already had a result. Luckily, this only happened with empty result sets, so the query was fast, and didn’t overload the server.
The correct code would be:
-
if ($results === false)
-
…
I’ve lost quite some time over this, so I’m posting this as a reminder: if possible, use strict checking.
Isn’t the if(!$result) equal to if($result === false)? I always thought it is.
Nope, checking for (!$result) is the same as ($result == false).
Uf. Now I know. Thanks