How to Check if an Array is Empty in PHP
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
- Managing PHP Dependencies with Composer
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a Node app using Docker
- Getting Started with Sass
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Using Axios to Pull Data from a REST API