Check whether an array is empty [duplicate]

I have the following code

<?php

$error = array();
$error['something'] = false;
$error['somethingelse'] = false;

if (!empty($error))
{
    echo 'Error';
}
else
{
    echo 'No errors';
}

?>

However, empty($error) still returns true, even though nothing is set.

What's not right?


There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:

$errors = array_filter($errors);

if (!empty($errors)) {
}

array_filter() function's default behavior will remove all values from array which are equal to null, 0, '' or false.

Otherwise in your particular case empty() construct will always return true if there is at least one element even with "empty" value.


You can also check it by doing.

if(count($array) > 0)
{
    echo 'Error';
}
else
{
    echo 'No Error';
}

Try to check it's size with sizeof if 0 no elements.