Count Versus Empty

This post is going to explore the reasoning behind using the empty() function over the
count() function when doing tests on arrays.

When working with any programming language, you are going to do a lot of work with iteration. Looping through massive arrays happens all the time. Sometimes you just want to see if there is even any information in the array before you start working with it. It is good practice to set an empty array before you even start working on it, and then filling it as you go.

So for instance, you need to fetch information from a database. Often you won’t actually know the amount of data coming out of the database from a query. Sometimes there may be none at all, but other times there may be millions of rows that fit your criteria. The following would be a good example of filling an array with data provided by a database query.

// Initialize empty array //
$array = array();

// Try | Catch block for SQL //
try {    
    // Database connection //
    $db = new PDO('mysql:dbname=your_database;host=127.0.0.1;', 
                  'uName', 'pWord');
    
    // Example SELECT statement //
    $sql = "SELECT `results` FROM `table` WHERE `condition`='met'";

    // Query //
    foreach ($db->query($sql) as $row) {
        // Fill array with results //
        $array[] = $row;
    }
} catch (PDOException $e) {
    echo $e->getMessage();
}

Simple enough.

We just queried the database and put all of the rows coming out that met our criteria into an array that we can use elsewhere. Lets say this is a search query for a humongous site. There are literally 1,000,000 rows of data that matched our criteria. Not only will it take a little while to fill our array, when we use the count() function to check if there were any results, it will cycle through the array to count how many elements actually exist within it. This isn’t that bad with smaller queries, but with larger ones like our example this will take even longer to do. Not very appealing is it.

// Check if $array is still empty //
if(count($array) == 0) {
    echo 'We found nothing.';
} else {
    // Work some magic //
}

But, If we were to use the empty() function, it would simply check to see weather the array contains elements or not. It returns a simple boolean true or false. There is no extra overhead or memory usage to maintain the array while iterating and counting through it, it just checks whether there is something in it or not.

// Check if array is still empty //
if (empty($array)) {
    echo 'We found nothing.';
} else {
    // Work some magic //
}

As you can see, using empty() over count() is probably a better idea unless you want to use the count for something else like:

$count = count($array);

if($count == 0) {
    echo 'We found nothing.';
} else {
    echo 'We found ' . $count . ' results';
}

At least then the count() is dual purpose and has a reason in our code. If knowing the count is irrelevant, than I suggest using empty() when possible. As a reminder to this, NULL is a value, while it may mean there is not information present, it still has a value, and will return a value, which means, not empty.

This entry was posted in Development, PHP and tagged , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply