Check if an Array is Empty or Not in PHP

In this post, we will explore how to check if an array is empty in PHP using the empty() function and the count() function. I’ll provide you with the example code and then modify it in different ways to demonstrate how to check if an array is empty using different methods.

Let’s jump into the examples.

If a PHP Array is empty – Examples

EXAMPLE 1

Using the empty() function:

$Array = []; // This is an empty array 
if (empty($Array)) { 
    echo "The array is empty."; 
} else { 
    echo "The array is not empty."; 
}

OUTPUT

The array is empty.

EXAMPLE 2

Using count() function:

$customArray = array();

if (count($customArray ) == 0) {
    echo "The array is empty.";
} else {
    echo "The array is not empty.";
}

OUTPUT

The array is empty.

EXAMPLE 3

Using shorthand ternary operator:

$myArray = array(); // This is an empty array 
echo (empty($myArray)) ? "The array is empty." : "The array is not empty.";

OUTPUT

The array is empty.

Conclusion

These examples demonstrate various ways to check if an array is empty in PHP. You can choose the one that suits your coding style and preferences.

Leave a Reply