Tuesday, September 29, 2015

Check whether an array is empty in PHP

If you want to check whether an array is empty or not, you will need to use the fuction array_filter() before checking for emptiness. By default, an empty array still contains a null, 0, '' or false element. So if an array is empty in front of us, chances are that it is not empty inside php code. But array_filter() function is there to the rescue. array_filter() strips the array from null, 0, '' and false elements.

Suppose we have an array like $_FILES['file']['name'].
Then empty($FILES['file']['name']) returns false whether the array is empty or not.
So the work around is first use the function array_filter().
$result_array = array_filter($_FILES['file']['name'])
Now empty($result_array) returns true if the array is empty and false if the array is not empty.

Usage:


$result_array = array_filter($_FILES['file']['name']);
if(empty($result_array))
{
    //array is empty condition
}
else
{
    //array is not empty condition
}

No comments: