Here I will show you four ways to check whether a PHP array is empty.
1. Using the empty() function
The PHP empty()
function determines whether a variable is empty. If the given variable is empty, this function will return true
else it will return false
.
empty($variable)
<?php
$a = [];
if(empty($a)){
echo "The array is empty.";
}
else{
echo "The array is not empty.";
}
The array is empty.
2. array count() function
The PHP count()
function is used to count the number of elements of an array. So we can use this function to check the length of an array, and if the length of an array is 0 then it means the array is empty.
// mode parameter is optional
count(array, mode)
<?php
$a = ["Apple", "Banana"];
if(count($a) === 0){
echo "The array is empty.";
}
else{
echo "The array is not empty.";
}
The array is not empty.
3. sizeof() function
The sizeof()
function is the alias of the count()
function, so you can use this function instead of the count()
function (both are the same). It is totally up to you which one you use.
<?php
$a = [];
if(sizeof($a) === 0){
echo "The array is empty.";
}
else{
echo "The array is not empty.";
}
The array is empty.
4. Using array_values() function with isset()
array_values(array)
– this function returns all the values from the array and indexes the array numerically.isset($var)
– this function returns true if the given variable exist and has any value other tahn null, return false otherwise.
Note: This is not preferable way to check whether an array is empty. Don’t use it, use one of the above three methods (specially empty()
).
<?php
$a = [];
if(isset(array_values($a)[0])){
echo "The array is not empty.";
}
else{
echo "The array is empty.";
}
The array is empty.