98

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

7 Answers 7

216

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>';
}
Sign up to request clarification or add additional context in comments.

14 Comments

I'm curious to know if this is faster than the implode method I suggested. Any benchmark around?
array_filter() was already mentioned by @dogmatic69. About performance - I believe simple foreach should be faster than both array_filter() and implode().
@xzyfer, if(implode($array)) echo '..' would print '..' even if one array element would be (string)"0". About foreach being slower than array_filter() - are you sure? How is removing array elements one-by-one faster than just reading array elements?
@xzyfer, I did some tests - using array_filter() just to check if any value is filled is at least few times slower than basic foreach loop with some boolean variable for storing result and break on first invalid value. Even with array_filter() being a "native PHP function", it can't really be faster than foreach as it has to create new array variable.
i upvoted, still i am a bit surprised this was actually accepted, because it does not fullfill the requirement, does it? If you put say, requestID=0 and status=0 this will result in "please enter a value" when there were clearly values.
|
26

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

Please note this is a safe way to consider values like 0 or "0" as not empty. The accepted answer using an empty array_filter callback will consider such values empty, as it uses the empty() function. Many form usages would have to consider 0 as valid answers so be careful when choosing which method works best for you.

17 Comments

YOu could remove the strlen call to make this more efficient. if(implode($array)) echo '..'
@xzyfer, if $str is (string)'0', then strlen($str) == 0 evaluates to false, while !$str evaulates to true, therefore strlen($str) == 0 can't be replaced with !$str.
@kasimir the callback function of array_filter is optional and the manual clearly states If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed. So, using array_filter is not less correct than this, it's just a diffrent method ;-)
Since the OP provided no sample data and no specific description of what "empty" means and because this page is being used as a canonical, answers should be very careful to provide robust explanations and include caveats where their answers may provide unexpected results. array_filter() and empty() are too often misused/misunderstood by php developers.
@mickmackusa thanks for your comment, I added a note to my answer reflecting that.
|
9

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

function isArrayEmpty(array $array): bool {
    foreach($array as $key => $val) {
        if ($val !== '' && $val !== null) // remove null check if you only want to check for empty strings
            return false;
    }
    return true;
}

2 Comments

empty() may provide false-positive results. See the manual about how the function treats falsey values. I would recommend the call of strlen() instead.
Thanks for the reminder about falseyness @mickmackusa, I've updated it to explicity check for empty string.
3

you don't really need it.
You're going to validate these fields separately and by finishing this process you can tell if array was empty (or contains invalid values, which is the same)

3 Comments

interesting! I wonder if this is faster than imploding the array.
@Capsule for the array size of 6, you will never ever see the slightest difference, even you spend whole your life checking arrays. for the sizes more than 1000 I'd suggest not to use arrays at all.
Since we are talking about websites, you have to multiply that per your number of visitors. An array of 1000 or 100 visitors computing an array of 10 is the same in term of CPU cost. You can't decide to stop using arrays because your website is gaining some popularity ;-)
3

simplify use this way:

$array = []; //target array
$is_empty = true; //flag

foreach ($array as $key => $value) {
    if ($value != '')
        $is_empty = false;
}
if ($is_empty)
    echo 'array is empty!';
else
    echo 'array is not empty!';

1 Comment

We should see a break in this script. Your answer is missing its educational explanation. This is effectively the same answer as stackoverflow.com/a/38447764/2943403 but a worse version.
-1

I had the same question but wanted to check each element in the array separately to see which one was empty. This was harder than expected as you need to create the key values and the actual values in separate arrays to check and respond to the empty array element.

print_r($requestDecoded);
$arrayValues = array_values($requestDecoded);  //Create array of values
$arrayKeys = array_keys($requestDecoded);      //Create array of keys to count
$count = count($arrayKeys);
for($i = 0; $i < $count; $i++){  
    if ( empty ($arrayValues[$i] ) ) {         //Check which value is empty
        echo $arrayKeys[$i]. " can't be empty.\r\n";
    } 
}

Result:

Array
(
    [PONumber] => F12345
    [CompanyName] => Test
    [CompanyNum] => 222222
    [ProductName] => Test
    [Quantity] =>
    [Manufacturer] => Test
)

Quantity can't be empty.

1 Comment

what? Just use foreach($array as $key => $value) and test if $value is empty of not.
-4

this is pretty simple:

foreach($array as $k => $v)
{
    if(empty($v))
    {
        unset($array[$k]);
    }
}
$show_error = count($array) == 0;

you would also have to change your encapsulation for your array values to double quotes.

8 Comments

He doesn't need a number. Just 1 is enough
What?, He wanted to know if all the elements are empty, there is no number just a boolean
I think what Col. is crassly saying is that in PHP both count($array) == 0 and count($array) evaluate to true so the extra comparison and assignment steps are unnecessary overheard. Although assignments cost very little in php.
Ahhh yea, it does not really make a huge difference but I would rather work with boolean's most of the time, I don't get why the down votes though, its a working method and creates him the result required.
to say if an array is empty or not, it is enough to find only ONE filled element. it is called LOGIC.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.