How to Check Whether an Array Is Empty in PHP

Sometimes a software crash or other unexpected circumstances can occur because of an empty array. Hence, it is crucial to detect empty arrays beforehand and avoid them. This tutorial represents how to inspect whether a particular array is empty or not in PHP.

Let’s check out several useful means that will help you meet that goal.

Watch a course Learn object oriented PHP

Applying the empty() Function

The first method is applying the empty() function as shown in the example below:

<?php

$phone = [];
echo empty($phone) ? "Array is empty." : "Array is not empty.";

?>

The output of this code will indicate that the array is empty.

Applying the count() Function

The next function to use for detecting an empty array is the count() function. This function differs from the one above: it is aimed at counting the elements inside an array.

This function returns 0 once the array is empty. Otherwise, the number of elements will be returned. In the case below, the result is 0. Thus, the given array is empty:

<?php

$phone = [];
echo count($phone);

?>

Now, let’s see another example where the number of the elements is returned:

<?php

$phone = ["00000", "11111", "22222", "33333"];
echo count($phone);

?>

The output of this example is 4. It means that the array includes 4 elements.

Applying the sizeof() Function

The third method is using the sizeof() function. Globally, it is used for checking the array size. When its size is 0, then the array is considered empty. Otherwise, it’s not empty.

Here is an example of using the sizeof() function:

<?php

// Declare an empty array
$empty_array = [];

// Use array index to check
// array is empty or not
if (sizeof($empty_array) == 0) {
  echo "Empty Array";
} else {
  echo "Non-Empty Array";
}

?>

In the output, it will be indicated that the given array is empty.