How to determine which check box is selected?

How to check in PHP whether checkbox checked or not?

+43
html input checkbox checked php
Feb 15 '10 at 21:04
source share
5 answers

If the check box is selected, the value of the flag will be transferred. Otherwise, the field is not transmitted in the HTTP message.

 if (isset($_POST['mycheckbox'])) { echo "checked!"; } 
+65
Feb 15 '10 at 21:06
source share

you can verify that isset() or empty() is checked (checking it explicitly isset), or

eg

  <input type='checkbox' name='Mary' value='2' id='checkbox' /> 

here you can check

 if (isset($_POST['Mary'])) { echo "checked!"; } 

or

 if (!empty($_POST['Mary'])) { echo "checked!"; } 

the above will check only one thing, if you want to do for many than you can make an array instead of writing a separate flag for all, try

 <input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br /> <input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br /> <input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br /> 

Php

  $aDoor = $_POST['formDoor']; if(empty($aDoor)) { echo("You didn't select any buildings."); } else { $N = count($aDoor); echo("You selected $N door(s): "); for($i=0; $i < $N; $i++) { echo htmlspecialchars($aDoor[$i] ). " "; } } 
+27
Dec 04 '12 at 18:26
source share

try it

 <form action="form.php" method="post"> Do you like stackoverflow? <input type="checkbox" name="like" value="Yes" /> <input type="submit" name="formSubmit" value="Submit" /> </form> <?php if(isset($_POST['like']) { echo "You like Stackoverflow."; } else { echo "You don't like Stackoverflow."; } ?> 

Or that

 <?php if(isset($_POST['like']) && $_POST['like'] == 'Yes') { echo "You like Stackoverflow."; } else { echo "You don't like Stackoverflow."; } ?> 
+6
Feb 15 '10 at 21:06
source share

If you don’t know what flags are on your page (for example: if you dynamically create them), you can simply put a hidden field with the same name and value 0 directly above the flag.

 <input type="hidden" name="foo" value="0" /> <input type="checkbox" name="foo" value="1"> 

This way you get 1 or 0 based on whether the checkbox is selected or not.

+2
Jul 24 '15 at 4:02
source share

I love short arms like this:

 $isChecked = isset($_POST['myCheckbox']) ? "yes" : "no"; 
0
Jul 17 '17 at 21:00
source share



All Articles