PHP Radio Button

Summary: in this tutorial, you’ll learn how to create a form with radio buttons and handle radio groups in PHP.

Introduction to radio buttons

To create a radio button, you use the <input> element with the type radio. For example:

<input type="radio" name="contact" id="contact_email" value="email" />
Code language: HTML, XML (xml)

A radio button doesn’t have a label. Therefore, you should always use a radio button with a <label> element like this:

<input type="radio" name="contact" id="contact_email" value="email"/> <label for="contact_email">Email</label>
Code language: HTML, XML (xml)

To associate a radio button with a <label> element, the value of the for attribute of the label needs to be the same as the value of the id of the radio button.

A radio button has two states: checked and unchecked.

When you link a label with a radio button, you can check the radio button by clicking the label or the radio button itself. Hence, the label increases the usability of the radio button because it expands the selection area.

Alternatively, you can place the radio button within a <label> element like this:

<label> <input type="radio" name="contact_email" value="email"> Email </label>
Code language: HTML, XML (xml)

In this case, the radio links to the label without matching the for and id attributes.

To select a radio button automatically when the page loads for the first time, you can use the checked Boolean attribute:

<input type="radio" name="contact" id="contact_email" value="email" checked /> <label for="contact_email">Email</label>
Code language: HTML, XML (xml)

Define a radio group

In practice, you often use the radio buttons in a group. A group of radio buttons is called a radio group. A radio group allows you to select only one radio button at a time.

If you select any radio button in a group, the currently-selected radio button in the same group is automatically deselected.

To define a radio group, you assign the same name to all the radio buttons in the same group.

The following example defines a radio group that consists of two radio buttons.

<input type="radio" name="contact" id="contact_email" value="email" /> <label for="contact_email">Email</label> <input type="radio" name="contact" id="contact_phone" value="phone" /> <label for="contact_phone">Phone</label>
Code language: HTML, XML (xml)

Handle radio buttons in PHP

When a form has a radio button with a name, you can get the checked radio button by accessing either $_POST or $_GET array, depending on the request method.

If a radio button is not checked, the $_POST or $_GET does not contain the key of the radio button. Therefore, you need to use the isset() function to check whether a radio button is checked or not:

isset($_POST['radio_name'])
Code language: PHP (php)

Alternatively, you can use the filter_has_var() function:

filter_has_var(INPUT_POST, 'radio_name')
Code language: JavaScript (javascript)

The filer_has_var() returns true if it finds the radio button name in the INPUT_POST.

If a radio button is checked, you get the value of the radio button from the $_POST using the radio button name:

$_POST['radio_name']
Code language: PHP (php)

PHP radio button example

We’ll create a simple form with a radio group. If you do not select any option and submit the form, it’ll show an error message. Otherwise, it’ll show the value of the selected radio button.

PHP Radio Button Demo

First, create the following directory and file structure:

. ├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.php
Code language: plaintext (plaintext)
FileDirectoryDescription
index.php.Contain the main logic that loads get.php or post.php depending on the HTTP request method
header.phpincContain the HTML header
footer.phpincContain the HTML footer
get.phpincContain the code for showing a form with radio buttons when the HTTP request is GET.
post.phpincContain the code for handling POST request
style.csscssContain the CSS code

Second, add the following code to the header.php file:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>PHP Radio Button</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <main>
Code language: HTML, XML (xml)

Third, add the following code to the footer.php file:

</main> </body> </html>
Code language: HTML, XML (xml)

Fourth, add the following code to the index.php file:

<?php require __DIR__ . '/inc/header.php'; $contacts = [ 'email' => 'Email', 'phone' => 'Phone' ]; $errors = []; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') { require __DIR__ . '/inc/get.php'; } elseif ($request_method === 'POST') { require __DIR__ . '/inc/post.php'; } require __DIR__ . '/inc/footer.php';
Code language: PHP (php)

How it works.

The $contacts array is used to generate radio buttons dynamically. In a real application, the data may come from a database table or a result of an API call.

The $errors array is used to collect the error messages.

To get the HTTP request method, you access the 'REQUEST_METHOD' key of the $_SERVER array. The strtoupper() function converts the request method to uppercase.

$request_method = strtoupper($_SERVER['REQUEST_METHOD']);
Code language: PHP (php)

The index.php file loads the get.php from the inc directory if the request is GET. When the form is submitted with the POST request, the index.php loads the post.php from the inc directory:

if ($request_method === 'GET') { require __DIR__ . '/inc/get.php'; } elseif ($request_method === 'POST') { require __DIR__ . '/inc/post.php'; }
Code language: PHP (php)

Fifth, create a form in the get.php file:

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post"> <div>Please choose your preferred method of contact:</div> <?php foreach ($contacts as $key => $value) : ?> <div> <input type="radio" name="contact" id="contact_<?php echo $key ?>" value="<?php echo $key ?>" /> <label for="contact_<?php echo $key ?>"><?php echo $value ?></label> </div> <?php endforeach ?> <div> <small class="error"><?php echo $errors['contact'] ?? '' ?></small> </div> <div> <button type="submit">Submit</button> </div> </form>
Code language: PHP (php)

The following code uses a foreach statement to generate a radio group from the $contacts array:

<?php foreach ($contacts as $key => $value) : ?> <div> <input type="radio" name="contact" id="contact_<?php echo $key ?>" value="<?php echo $key ?>" /> <label for="contact_<?php echo $key ?>"> <?php echo $value ?> </label> </div> <?php endforeach ?>
Code language: PHP (php)

The following code shows the error message from the $errors array. Note that we use the null coalescing operator (??) which is available in PHP 7+.

The expression $errors['contact'] ?? '' returns $errors['contact'] if it exists and is not null or ” otherwise.

<small class="error"><?php echo $errors['contact'] ?? '' ?></small>
Code language: PHP (php)

Finally, add the code that handles the POST request:

<?php // sanitize the contact $contact = filter_input(INPUT_POST, 'contact', FILTER_SANITIZE_STRING); // check the selected value against the original values if ($contact && array_key_exists($contact, $contacts)) { $contact = htmlspecialchars($contact); } else { $errors['contact'] = 'Please select at least an option.'; } if (count($errors)) { require __DIR__ . '/get.php'; } else { echo <<<html You selected to be contacted via <strong> $contact</strong>. <a href="index.php">Back to the form</a> html; }
Code language: PHP (php)

How the post.php works.

The filter_input() function sanitizes the value of the checked radio button. To make sure the submitted value is valid, we check it against the keys of the $contact array using the array_key_exists() function.

If the submitted value matches with one of the array keys, we show a message. Otherwise, we add an error message to the $errors array.

In the last if...else statement, we load the form (get.php) that shows an error message if the $errors array is not empty. Otherwise, we show a confirmation message.

Summary

  • Use the input with type="radio" to create a radio button.
  • Use the same name for multiple radio buttons to define a radio group.
  • Get the value of a checked radio via the $_POST (or $_GET) variable, depending on the request method.
Did you find this tutorial useful?