This article introduces how to handle radio and checkbox in a form with PHP and gives a live demo to demonstrate it.
HTML form
In a HTML form, you need to specify the name and value attributes in radio and checkbox elements. Specially the names for checkbox group need to end with []
, then the submitted checkbox data will be an array in the form handler. For a single checkbox, its name does not need to be end with []
, its handling is similar to the radio.
A form with radio and checkbox
HTML code
<form action="action.php" method="post">
<div>
<label for="name">Name:</label>
<input id="name" type="text" name="name" >
</div>
<div>
<input type="radio" name="gender" id="female" value="Female">
<label for="female">Female</label>
<input type="radio" name="gender" id="male" value="Male">
<label for="male">Male</label>
</div>
<div>
<input type="checkbox" name="sports[]" id="badminton" value="Badminton">
<label for="badmiton">Badminton</label>
<input type="checkbox" name="sports[]" id="tennis" value="Tennis">
<label for="tennis">Tennis</label>
<input type="checkbox" name="sports[]" id="table-tennis" value="Table Tennis">
<label for="table-tennis">Table Tennis</label>
<input type="checkbox" name="sports[]" id="swimming" value="Swimming">
<label for="swimming">Swimming</label>
<input type="checkbox" name="sports[]" id="other" value="Other">
<label for="other">Other</label>
</div>
</form>
Effect
PHP handling
In the PHP handler of the form above, if a radio is checked, the $_POST['gender']
will be its value. If no radio is checked, $_POST['gender']
will be unset (meaning isset( $_POST['gender'] )
is false). If one or more checkboxes are checked, $_POST['sports']
will be an array containing all the checked values, otherwise it will be unset.
PHP form handling code in the action.php
file:
<?php
if ( isset( $_POST['name'] ) ) {
echo '<p>Your name is ' . $_POST['name'] . '</p>';
} else {
echo '<p>Your name is unset.</p>';
}
// radio
if ( isset( $_POST['gender'] ) ) {
echo '<p>You are ' . $_POST['gender'] . '</p>';
} else {
echo '<p>Your gender is unset</p>';
}
// checkbox
// If the user did not select any sport, $_POST['sports'] will be unset.
if( empty( $_POST['sports'] ) ) {
echo 'You did not select any favorite sports.';
} else { // Return an array containing checked strings.
echo '<p>Your favorite sports:</br>';
foreach ( $_POST['sports'] as $s ) {
echo '- ' . $s . '</br>';
}
echo '</p>';
}
?>
See a live demo: Handling radio and checkbox in a form with PHP demo.