How to Check if an Array is Empty in PHP

Updated onbyAlan Morel
How to Check if an Array is Empty in PHP

In many cases, it is useful to know if the array you're working with is empty or not.

This can be to prevent errors, ensure data integrity, or just to know if you should do something or not.

In this post, we'll learn how you can check if an array is empty or not in PHP.

Using Empty()

The best way to check if an array is empty is to use the empty() function.

This function takes in your array and returns a boolean value, true if the array is empty, and false if it is not.

Let's start out with our example array:

PHP
$array = [];

Now let's use the empty() function to check if the array is empty:

PHP
$array = []; if (empty($array)) { echo('The array is empty.'); } else { echo('The array is not empty.'); }
BASH
The array is empty.

As expected, the array is empty, so the empty() function returned true.

Using Count()

Another way you can check if an array is empty is to use the count() function.

This function will return to you the number of elements in the array, so if the array is empty, it will return 0.

PHP
$array = []; if (count($array) === 0) { echo('The array is empty.'); } else { echo('The array is not empty.'); }
BASH
The array is empty.

Because this returns to you the number of elements in the array, you can use this information for anything else you need in your program.

Using sizeof()

The last way you can check if an array is empty is to use the sizeof() function.

This function will also return to you the number of elements in the array, so if the array is empty, it will return 0.

PHP
$array = []; if (sizeof($array) === 0) { echo('The array is empty.'); } else { echo('The array is not empty.'); }
BASH
The array is empty.

Conclusion

In this post, we learned several ways to check if an array is empty in PHP.

You can either use the empty() function, the count() function, or the sizeof() function.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.