This tutorial will discuss about unique ways to check if an array is empty or not in php.
Table Of Contents
Method 1: Using empty() function
The empty() function in PHP accepts a variable as an argument, and returns true if variable is empty i.e. either variable does not exists or it evaluates to false.
We can pass an array object in it, to check if an array is empty or not. If it returns true, then it means array is empty, otherwise it is not empty.
Let’s see the complete example,
Frequently Asked:
<?php // create an empty array $arr = array(); // Check if array is empty if (empty($arr)) { echo "Yes, the array is empty"; } else { echo "No, the array is not empty"; } ?>
Output
Yes, the array is empty
Method 2: Using count() function
The count() function in PHP accepts an array as an argument, and returns the number of elements in the array. If it returns 0, then it means that the array is empty, otherwise array is not empty.
Let’s see the complete example,
<?php // create an empty array $arr = array(); // Check if count of elements in array is 0 // Check if array is empty if (count($arr) == 0) { echo "Yes, the array is empty"; } else { echo "No, the array is not empty"; } ?>
Output
Yes, the array is empty
Summary
We learned about two ways to check if an array is empty or not in PHP