How to check an array is empty using PHP examples

How to check an array is empty using PHP examples

In this article lets explore how to check an array is empty using PHP with examples.

In PHP, we can check whether an array is empty using various methods. Here are three common ways to achieve this:

1. empty() function :

This is in built function of PHP to check if variable is empty. Returns boolean value. True if array is empty and false if not empty.


$myArray = array(); // An empty array
if (empty($myArray)) {
    echo "The array is empty.";
} else {
    echo "The array is not empty.";
}

// Output : The array is empty.

empty() – read document for more.

2. count() function :

This function will count number of elements in array. So if it returns 0 we can identify the array is empty.


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

// Output : The array is empty.

3. array comparison

We can check using empty array comparison so it it match we can identify the array is empty. This method is very uncommon in use as above two does the thing well but this is just another way we can do.


$myArray = array(); // An empty array
if ($myArray === array()) {
    echo "The array is empty.";
} else {
    echo "The array is not empty.";
}

//Output: The array is empty.

Choose the method that suits your coding style and requirements. All of these methods will effectively check whether an array is empty or contains no elements.

So that’s it on how to check an array is empty using PHP via examples.

See other articles on PHP here.