Radio Buttons in PHP
Let's now learn how to work with radio
in PHP. Let's make several radio buttons in
our form:
<form action="" method="GET">
<input type="radio" name="radio" value="1">
<input type="radio" name="radio" value="2">
<input type="radio" name="radio" value="3">
<input type="submit">
</form>
After submitting the form, the $_GET
array
will contain the value of the value
attribute
of the selected radio button, or null
,
if nothing was selected:
<?php
var_dump($_GET['radio']); // '1', '2', '3' or null
?>
When working with radio buttons, the same problem arises as with checkboxes. To solve this problem, let's add a hidden input:
<form action="" method="GET">
<input type="hidden" name="radio" value="0">
<input type="radio" name="radio" value="1">
<input type="radio" name="radio" value="2">
<input type="radio" name="radio" value="3">
<input type="submit">
</form>
You can also avoid introducing a hidden input by making one of the radio buttons selected by default:
<form action="" method="GET">
<input type="radio" name="radio" value="1" checked>
<input type="radio" name="radio" value="2">
<input type="radio" name="radio" value="3">
<input type="submit">
</form>
Using two radio buttons, ask the user for their gender. Display the result on the screen.