How to Check Whether an Array Is Empty in PHP

  1. Applying the empty () Function
  2. Applying the count() Function
  3. Applying the sizeof() Function

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.

A .Applying the empty () Function

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

<?php
$phone = array();
echo empty($phone) ? "Array is empty.": "Array is not empty.";
?>

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

B.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=array();
echo count($phone);
?>

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

<?php
$phone=array("00000","11111","22222", "33333");
echo count($phone);
?>

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

B.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 = 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.


Do you find this helpful?

Related articles