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!
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to deploy a MySQL Server using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API