Handling empty $_POST

I have this code…

        foreach($_POST['interest'] as $id => $interest){

And I just discovered that if the user doesn’t select any checkboxes I get this error…

What is the proper way to check if my $_POST array is empty?

Find out the value returned when the user does not select any checkboxes and amend your script:

// check value
   echo '<pre>'; var_dump( $_POST ); echo '</pre>';

// do your stuff
if ( $whateverIsValid )  {
   foreach($_POST['interest'] as $id => $interest) {
     ...
   }

}else{
   echo '??? No select boxes checked ???';
}

if (empty($_POST['interest'])) { ..array is empty or not exists.. }
1 Like

Without knowing the interest values your script could fail with the following two cases:

$_POST['interest'] = 0;
$_POST['interest'] = '0';

I prefer to use the following:

if ( isset( $_POST ) && 0 === count($_POST) ) {
 echo ' ..array is empty or not exists.. ';
}

Without knowing the full source script it is only a guess.

You’re right, better solution is:

if (!empty($_POST['interest']) && is_array($_POST['interest'])){
    // its now safe to use loop
    foreach($_POST['interest'] as $id => $interest) {            ...
        ...
    }
}
4 Likes

It seems that this is enough.

No. You need the is_array check too as empty() returns true for other scenarios such as an empty string “”, the value 0, etc.
http://php.net/manual/en/function.empty.php

Ternary Logic is great for this.

$var = isset( $_POST['interest'] ) ? filter_input(INPUT_POST, 'interest') : "default-value" ;

This is why I wrapped my example in

//POST validate
if(isset($_POST['interest']))

Just ckecking for not empty

if (!empty($_POST['interest'])

will still throw Undefined index: interest error

:

@djsmithme: only that this filter returns incorrect data due to the missing array flag. and you don’t event need the isset() here as the input filter does not error out if the data are missing (but returns NULL instead).

Huh??? :confused:

Not in my code. This is now working upon preliminary testing - I got sucked into something else so haven’t had a chance to thoroughly test stuff.

        if (!empty($_POST['interest'])){
            foreach($_POST['interest'] as $id => $interest){

$_POST[‘interest’] = 1 would return false so !empty($_POST[‘interest’]) would result in a non-array value that passes your condition. Thus you can’t loop it and will still get an error.

You need to use isset, empty and is_array to properly ensure you have an array of interests.

Just to restate… we are talking about checkbox array so if isset it should be an array not a string and unless the form was tampered with it should not be an empty array. And as OP stated the problem was when no checkboxes are checked and thus the index ‘interest’ does not exist.

So is this better?

        if (isset($_POST['interest']) && !empty($_POST['interest']) && is_array($_POST['interest'])){
            foreach($_POST['interest'] as $id => $interest){
                // Sanitize Values.
                $id = (int)$id;
                $interest = trim($interest);

                if (in_array($interest, $validInterestArray)){
                    // Valid Interest.

                    // Copy Form-Data into Response-Array.
                    //        **NOTE: This array shows all Interests that were checked in the form.
                    $interestResponseArray[$id] = $interest;

                }else{
                    // Invalid Interest.
                    // Do nothing...
                }
            }
        }else{
            echo "Some error";
        }
1 Like

Actually you can use only empty() because it does what isset() do, but also checks for non-false value

But what if a falsy value, such as 0, is a legal value? I think that was @John_Betong’s point earlier. empty runs the risk of giving you a false positive. isset is safer.

1 Like

You’re right but OP is looking for array with at least one item inside. So any other value will be wrong in his case.

I assume this is the safest, even if a tad overkill…

        if (isset($_POST['interest']) && !empty($_POST['interest']) && is_array($_POST['interest'])){

When I added $_POST[‘interest’]=1; it broke my code when I only checked for empty.

I’m indifferent to isset, but it can’t hurt! :smile:

1 Like

Which is why I recommended to also use is_array, that ensures you are working with an array of data, not just a value that !empty() would allow to pass through but isn’t an array. isset probably is overkill (my bad).

1 Like