Table of Contents
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.');
}
BASHThe 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.');
}
BASHThe 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.');
}
BASHThe 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!
How to Install Node on Windows, macOS and Linux
Getting Started with Svelte
Getting Started with Electron
How to Set Up Cron Jobs in Linux
How to deploy a .NET app using Docker
How to deploy a PHP app using Docker
Getting Started with Deno
How to Scrape the Web using Node.js and Puppeteer
Creating a Twitter bot with Node.js
Setting Up a Local Web Server using Node.js
Using Axios to Pull Data from a REST API
Getting Started with Moon.js
