Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

foreach checkbox POST in php

Basically my question is the following, how can i select on "Checked" checkbox's while doing a $_POST request in PHP, currently i have the checkbox's doing an array as shown below.

<input type="checkbox" value="1" name="checkbox[]">
<input type="checkbox" value="2" name="checkbox[]">
<input type="checkbox" value="2" name="checkbox[]">
<input type="checkbox" value="3" name="checkbox[]">

I want to be able to do something like this

foreach(CHECKED CHECKBOX as CHECKBOX) {
   echo CHECKBOX VALUE;
}

I've tried doing similar to that and it's not echoing anything.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
foreach($_POST['checkbox'] as $value) {

}

Note that $_POST['checkbox'] will only exist if at least one checkbox is checked. So you must add an isset($_POST['checkbox']) check before that loop. The easiest way would be like this:

$checkboxes = isset($_POST['checkbox']) ? $_POST['checkbox'] : array();
foreach($checkboxes as $value) {
    // here you can use $value
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...