Picks up checkbox values

Asked

Viewed 139 times

1

I need to get more than one checkbox value, if you have more than one value, example:

<input type="checkbox" name="combustivel[]" value="Marco">
<input type="checkbox" name="combustivel[]" value="Empres contratada">
<input type="checkbox" name="combustivel[]" value="Desconto">

In case I need to book the checkbox Marco and Desconto, how can I get these two?

I got this code off the web:

if(!empty($_POST['combustivel'])) {
  foreach($_POST['combustivel'] as $comb) {
          echo $comb;
  }
}

But the following warning comes:

Warning: Invalid argument supplied for foreach()....

  • Your code seems correct, I tested it with this example. Invalid argument supplied means that an array was expected and came something else.

  • Your code looks pretty good, maybe it’s something else. The type of request is really POST, isn’t it GET? To test this, run a var_dump($_POST); exit; before this foreach and see if the values have been returned.

  • @Lost? You mean the $Comb variable should be $Comb[], would that be?

  • See the return of print_r($_POST['combustivel']); should be an array. Put this before if

  • This error appears only when you do not select any option or always appears?

  • Whenever you try to get a data in an array, always print the result with print_r(); as @lost said, and for your case, I believe the sentence for the foreach must be foreach($_POST['combustivel] as $comb=>$valor){ echo $valor }.

Show 1 more comment

1 answer

1

Maybe this error is happening because no option has been selected, try to use is_array() instead of Empty().

if (is_array($_POST['combustivel'])) {
    foreach($_POST['combustivel'] as $comb) {
        echo $comb;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.