Checking if all the array items are empty PHP

Matt picture Matt · Feb 18, 2011 · Viewed 73.1k times · Source

I'm adding an array of items from a form and if all of them are empty, I want to perform some validation and add to an error string. So I have:

$array = array(
    'RequestID'       => $_POST["RequestID"],
    'ClientName'      => $_POST["ClientName"],
    'Username'        => $_POST["Username"],
    'RequestAssignee' => $_POST["RequestAssignee"],
    'Status'          => $_POST["Status"],
    'Priority'        => $_POST["Priority"]
);

And then if all of the array elements are empty perform:

$error_str .= '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>';

Answer

xzyfer picture xzyfer · Feb 18, 2011

You can just use the built in array_filter

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

So can do this in one simple line.

if(!array_filter($array)) {
    echo '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>';
}