getting a checkbox array value from POST

后端 未结 5 1743
一整个雨季
一整个雨季 2020-11-28 13:10

i am posting an array of checkboxes. and i cant get it to work. i didnt include the proper syntax in the foreach loop to keep it simple. but it is working. i tested in by tr

相关标签:
5条回答
  • 2020-11-28 13:25

    Your $_POST array contains the invite array, so reading it out as

    <?php
    if(isset($_POST['invite'])){
      $invite = $_POST['invite'];
      echo $invite;
    }
    ?>
    

    won't work since it's an array. You have to loop through the array to get all of the values.

    <?php
    if(isset($_POST['invite'])){
      if (is_array($_POST['invite'])) {
        foreach($_POST['invite'] as $value){
          echo $value;
        }
      } else {
        $value = $_POST['invite'];
        echo $value;
      }
    }
    ?>
    
    0 讨论(0)
  • 2020-11-28 13:26
    // if you do the input like this
    <input id="'.$userid.'" value="'.$userid.'"  name="invite['.$userid.']" type="checkbox">
    
    // you can access the value directly like this:
    $invite = $_POST['invite'][$userid];
    
    0 讨论(0)
  • 2020-11-28 13:32

    I just used the following code:

    <form method="post">
        <input id="user1" value="user1"  name="invite[]" type="checkbox">
        <input id="user2" value="user2"  name="invite[]" type="checkbox">
        <input type="submit">
    </form>
    
    <?php
        if(isset($_POST['invite'])){
            $invite = $_POST['invite'];
            print_r($invite);
        }
    ?>
    

    When I checked both boxes, the output was:

    Array ( [0] => user1 [1] => user2 )
    

    I know this doesn't directly answer your question, but it gives you a working example to reference and hopefully helps you solve the problem.

    0 讨论(0)
  • 2020-11-28 13:35

    Check out the implode() function as an alternative. This will convert the array into a list. The first param is how you want the items separated. Here I have used a comma with a space after it.

    $invite = implode(', ', $_POST['invite']);
    echo $invite;
    
    0 讨论(0)
  • 2020-11-28 13:38

    Because your <form> element is inside the foreach loop, you are generating multiple forms. I assume you want multiple checkboxes in one form.

    Try this...

    <form method="post">
    foreach{
    <?php echo'
    <input id="'.$userid.'" value="'.$userid.'"  name="invite[]" type="checkbox">
    <input type="submit">';
    ?>
    }
    </form>
    
    0 讨论(0)
提交回复
热议问题