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!
Getting Started with TypeScript
How to Serve Static Files with Nginx and Docker
How to deploy a .NET app using Docker
How to build a Discord bot using TypeScript
How to deploy a PHP app using Docker
Getting Started with Deno
How to deploy an Express app using Docker
How to Scrape the Web using Node.js and Puppeteer
Getting User Location using JavaScript's Geolocation API
Creating a Twitter bot with Node.js
Using Push.js to Display Web Browser Notifications
Getting Started with Vuex: Managing State in Vue
