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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$Array = []; // This is an empty array
if (empty($Array)) {
echo "The array is empty.";
} else {
echo "The array is not empty.";
}
$Array = []; // This is an empty array if (empty($Array)) { echo "The array is empty."; } else { echo "The array is not empty."; }
$Array = []; // This is an empty array 
if (empty($Array)) { 
    echo "The array is empty."; 
} else { 
    echo "The array is not empty."; 
}

OUTPUT

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
The array is empty.
The array is empty.
The array is empty.

EXAMPLE 2

Using count() function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$customArray = array();
if (count($customArray ) == 0) {
echo "The array is empty.";
} else {
echo "The array is not empty.";
}
$customArray = array(); if (count($customArray ) == 0) { echo "The array is empty."; } else { echo "The array is not empty."; }
$customArray = array();

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

OUTPUT

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
The array is empty.
The array is empty.
The array is empty.

EXAMPLE 3

Using shorthand ternary operator:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$myArray = array(); // This is an empty array
echo (empty($myArray)) ? "The array is empty." : "The array is not empty.";
$myArray = array(); // This is an empty array echo (empty($myArray)) ? "The array is empty." : "The array is not empty.";
$myArray = array(); // This is an empty array 
echo (empty($myArray)) ? "The array is empty." : "The array is not empty.";

OUTPUT

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
The array is empty.
The array is empty.
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