Original reproduced from: http://www.html-form-guide.com/php-form/php-form-checkbox.html
Single checkbox
shaped like:
<formAction= "checkbox-form.php"Method= "POST">Do you need wheelchair access? <inputtype= "checkbox"name= "Formwheelchair"value= "Yes" /> <inputtype= "Submit"name= "Formsubmit"value= "Submit" /></form>
If '$_POST[‘formWheelchair‘]`的值是"Yes",那么该checkbox被勾选
If the checkbox is not checked, then ' $_POST[‘formWheelchair‘]`
will not be set
Here's how PHP handles the form:
<? If(isset($_post[' Formwheelchair ')] && $_post[' Formwheelchair '] = = ' Yes ') {echo "need wheelchair access." ;} Else { echo "Do not need wheelchair access." ;} ? >
The Isset method can be used to determine if ' formwheelchair ' is checked, and if not, returns false
CheckBox combination
The recurring scenario is multiple checkboxes, as shown in the following example:
<formAction= "checkbox-form.php"Method= "POST">which buildings do you want access to?<BR/><inputtype= "checkbox"name= "formdoor[]"value= "A" />Acorn Building<BR/><inputtype= "checkbox"name= "formdoor[]"value= "B" />Brown Hall<BR/><inputtype= "checkbox"name= "formdoor[]"value= "C" />Carnegie Complex<BR/><inputtype= "checkbox"name= "formdoor[]"value= "D" />Drake Commons<BR/><inputtype= "checkbox"name= "formdoor[]"value= "E" />Elliot House<inputtype= "Submit"name= "Formsubmit"value= "Submit" /> </form>
Note that the checkbox has exactly the same name, (formdoor[], and also note that each name ends with [], using [] to make an array of the values of each checked check box in PHP, $_post[' Formdoor ') Returns an array of values that have the check box checked
For example, I tick all the checkboxes and $_POST[‘formDoor‘]
will return an array of {a,b,c,d,e}, the following example of how to remove the array values and display them:
<?PHP$aDoor=$_post[' Formdoor ']; if(Empty($aDoor)) { Echo("You didn ' t select any buildings.")); } Else { $N=Count($aDoor); Echo("You selected$NDoor (s): "); for($i= 0;$i<$N;$i++) { Echo($aDoor[$i] . " "); } }?>
Visible ' empty () ' can be used to empty the array, ' count ' for the array count
Check whether a particular option is checked
functionIsChecked ($chkname,$value) { if(!Empty($_post[$chkname])) { foreach($_post[$chkname] as $chkval) { if($chkval==$value) { return true; } } } return false; }
Questions and Answers from StackOverflow
If your HTML page looks like this:
<type= "checkbox" name= "Test" value= " Value1 ">
After submitting the form you can check it with:
isset ($_post[' Test '])
Or
if ($_post[' test '] = = ' value1 ') ...
Working with forms in PHP-checkbox