This post will discuss how to determine whether an array is empty in PHP.

1. Using empty() function

A variable is considered to be empty in PHP if it doesn’t exist, or if its value equals false. The empty() function returns true if a variable is empty, false otherwise. You can use the empty() function to check for empty arrays as well. It returns true if there are no elements present in the array and false otherwise.

Download  Run Code

 
The empty() function will return true for all falsey values (like false, 0, “”, null, array(), etc.). If you specifically want to check for empty arrays, you can first check for an array using is_array() function.

Download  Run Code

2. Using negation operator

Because an empty array is false in PHP, the call to empty() can be replaced with the logical negation operator (!). The logical negation operator implicitly converts its operand to type bool, and returns a boolean value that is opposite to that of the converted operand. As with the empty() function, you can determine whether the given variable is an array with is_array() function.

Download  Run Code

3. Using identity comparison operator

Alternatively, you can use the identity comparison operators (=== and !==) to check for empty arrays in PHP. The expression $a === $b returns true if $a is equal to $b, and they are of the same type. You can compare your variable against the array() construct with === operator, which returns true only for empty arrays and false otherwise.

Download  Run Code

 
Since PHP 5.4, you can use the short array syntax []. It works in a similar way as the array() construct, but avoids the overhead of calling the function.

Download  Run Code

4. Using count() function

You can also count the total number of elements in the array. The count() or sizeof() function will work for arrays or objects that implement Countable. For other falsey values, count() throws Fatal error: Uncaught TypeError: count(): The first argument ($value) must be of the type Countable|array.

Download  Run Code

5. Using array_filter() function

If you need to check if the array contains all falsey values, you can pass your array to the array_filter() function and compare the resultant array against array() construct or [] syntax with the === operator. The array_filter() function filters elements of an array using a callback function. If no callback is supplied, all falsey values will be removed from the array. The following solution demonstrates this:

Download  Run Code

That’s all about checking for an empty array in PHP.