Home > Thoughts > array() == false

array() == false

March 7th, 2009

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:

  1. $results = $memcache->get('key');
  2. if (!$results)
  3. {
  4.   $results = $this->fetchFromDb();
  5.   $memcache->set('key', $results);
  6. }
  7. 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:

  1. if ($results === false)

I’ve lost quite some time over this, so I’m posting this as a reminder: if possible, use strict checking.

Share and Enjoy:
  • Print
  • del.icio.us
  • Twitter
  • Facebook
  • Digg
  • Google Bookmarks
  • Technorati
  • FriendFeed
  • Netvibes
  • Slashdot
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • email
Author: Gašper Categories: Thoughts Tags: ,
  1. March 8th, 2009 at 12:12 | #1

    Isn’t the if(!$result) equal to if($result === false)? I always thought it is.

  2. March 8th, 2009 at 12:58 | #2

    Nope, checking for (!$result) is the same as ($result == false). :)

  3. March 9th, 2009 at 09:06 | #3

    Uf. Now I know. Thanks :)

  1. No trackbacks yet.