简体   繁体   中英

remember checkbox value if its checked array name in a form php

lets say we have this:

echo '<form method="post">
        <div class="form-group">
            <table class="table table-bordered table-hover table-striped" style="width:auto">
              <tr>
                <td><label for="array">ARRAY_NAME</label></td>        
                <td>
                 <input type="checkbox" name="array[]" value="1" /> option1<br />
                 <input type="checkbox" name="array[]" value="2" /> option2
                </td>
              </tr>
              <tr>
                <td><label for="array2">ARRAY_NAME2</label></td>        
                <td>
                 <input type="checkbox" name="array2[]" value="1" /> option1<br />
                 <input type="checkbox" name="array2[]" value="2" /> option2
                </td>
              </tr>
              <tr>
                <td><label for="array3">ARRAY_NAME3</label></td>        
                <td>
                 <input type="checkbox" name="array3[]" value="1" /> option1<br />
                 <input type="checkbox" name="array3[]" value="2" /> option2
                </td>
              </tr>
           </table>
        </div>
        <button type="submit" name="submit" class="btn btn-success">Submit</button>
</form>';

I tried to implement this code: <?php echo (isset($_POST['array1[0]']) && $_POST['array1[0]'] == 1) ? "checked='checked'" : "" ?> <?php echo (isset($_POST['array1[0]']) && $_POST['array1[0]'] == 1) ? "checked='checked'" : "" ?>

but it didn't work! It only works if you have name="array1" and name="array2" . this way I'm thinking I can save multiple data in a parent array saved! Like this form[array1[],array2[],array3[]] .

Can someone give me a solution because I'm stuck! Thanks in advance guys!!

When you put square brackets in the name of form control, PHP will inflate that set of elements with similar names into an array.

You need to access:

$_POST['array1'][0]

not

$_POST['array1[0]'] // This is incorrect

(You also need to match the actual name of your control: Your HTML has array , array2 and array3 but not array1 )

You are trying to access the values incorrectly.

You can access a array posted like this:

echo $_POST['array1'][0];

php.net/$_POST See the first comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM