PHP: Fastest way to check if an array is empty

I just posted benchmarks for checking for an empty string that I ran when looking to improve the efficiency of an application. Another simple benchmark I ran was for ways to check if an array is empty.

Like strings, there are a ton of ways to check if am array is empty. These here are not exhaustive, but a few that I chose to test:

  1. !$array
  2. $array == false
  3. empty($array)
  4. count($array) == 0
  5. $array == array()
My short disclaimer: You should know that these methods are not all perfect for every use case. For example, #1 & #2 would be true if $array was a “true” boolean or #3 would be true even if $array was null or “0”. Take caution to understand each of these when using them. You should also note that benchmarks will vary greatly depending on a number of factors, like PHP version, hardware, and operating system. The size of the array could also have a factor.

I ran each of these checks 1 million times. The machine is 32-bit Fedora, 1.7GB RAM c1.medium Amazon ec2 instance with Apache. PHP is 5.2. I checked with a blank array(). For what it’s worth, I also checked array(‘a’), which had similar results.

PHP 5.2 on Fedora Results

  • !$array = 1.35s
  • empty($array) = 1.45s
  • $array == false = 1.46s
  • $array == array() = 1.80s
  • count($array) == 0 = 2.34s

Similar to the results from testing strings, the winner is consistently !$array. I’m not a big fan of using this in code because it implies the variable is boolean (the same goes for #2), but it does evaluate to false. empty() is actually not a bad choice here and is considerably faster for checking arrays than strings. Just like strlen() for strings, testing count($array) == 0 is a poor choice because it has to perform two operations.

PHP 5.3 on Windows 7 Results

I also ran the same script on my Windows machine (6GB, Quad core, Apache, PHP 5.3) with quite different results. Again, it would be better to compare 5.2 to 5.3 on the same machine. Perhaps I will if I get some spare time, but I used what I had access to.

  • empty($array) = 0.65s
  • !$array = 0.65s
  • $array == false = 0.68s
  • $array == array() = 0.80s
  • count($array) == 0 = 1.72s

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>