Checking if all the array items are empty PHP

04/27/2020 22:30:01

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>';

Verified Answer (167 Votes)

02/18/2011 16:51:58

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>';
}
167

Answer #2 (18 Votes)

02/18/2011 16:45:40

implode the array with an empty glue and check the size of the resulting string:

<?php if (strlen(implode($array)) == 0) echo 'all values of $array are empty'; ?>
18

Answer #3 (7 Votes)

07/19/2016 05:18:17

An older question but thought I'd pop in my solution as it hasn't been listed above.

function isArrayEmpty($array) {
    foreach($array as $key => $val) {
        if ($val !== '')
            return false;
    }
    return true;
}
7
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.