The quickest method for determining if your PHP array is empty

Posted by

The fastest way to check if an array is empty

To check whether a PHP array is empty or not, use theĀ empty()Ā function:

$foo = [];

// true
var_dump(empty($foo));

$bar = ['Foo', 'Bar', 'Baz'];

// false
var_dump(empty($bar));

This is how I prefer to do it. However, there are several ways to determine whether an array is empty, like:

  • Using theĀ count()Ā (orĀ sizeof()) function to count the number of elements in the array and check if itā€™s equal to zero.Ā count()Ā can even count the numbers of entries inside a multidimensional array.
  • Using the not operator (!). If the array does hold any value, the not operator will returnĀ true.

You can choose to end the process there or continue reading to learn how to utilise these functions in-depth to look for empty arrays.

Other ways to check if an array is empty

The count() function

Another way to check if your array is empty is to use the count() function. The function returns an integer depending on the number of items inside, or zero if itā€™s empty.

You can even use it withĀ CountableĀ objects.

echo count(['Foo', 'Bar', 'Baz']);

You can recursively count the number of items in multidimensional arrays by using the COUNT_RECURSIVE constant for the second parameter.

$array = [
    'Foo' => [
        'Bar' => ['Baz'],
    ],
];

// 3
$count = count($array, COUNT_RECURSIVE);

// If $count is greater than zero.
if ($count > 0) {
    // The array is not empty.
} else {
    // The array is empty.
}

The sizeof() function

sizeof()Ā is an alias of count() and can be used on arrays in the same way.Ā PHP actually has a lot of aliases for various functions.

Thereā€™s nothing to add, you already know how to use it:

The not (!) operator

One not super intuitive way to check if your array is not empty is to use the not operator (!).

$foo = [];

if (! $foo) {
    echo '$foo is empty.';
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x