Checkbox, Radio and Select Inputs

sa sahaya jerish Updated 17 Oct 2026
7 min read ·Lesson 97 of 248
In this post

Checkboxes, radio buttons, and select lists let users choose from options instead of typing. They look simple, but each sends data differently — or not at all when nothing is chosen — and the submitte

Checkboxes, radio buttons, and select lists let users choose from options instead of typing. They look simple, but each sends data differently — or not at all when nothing is chosen — and the submitted values can be manipulated just like text fields. This lesson shows how each input submits data, how to validate choices safely, and how to re-select the user's choices when a form is shown again.


How Each Input Submits Data

InputHTMLSent When$_POST Value
Single checkbox<input type="checkbox" name="terms" value="yes">Only if checked'yes' (or 'on' without value)
Checkbox group<input type="checkbox" name="skills[]" value="php">Only checked boxesArray: ['php', 'mysql']
Radio group<input type="radio" name="plan" value="pro">Only if one is selected'pro'
Select<select name="city">Always (selected option)'MAA'
Multiple select<select name="langs[]" multiple>Only selected optionsArray: ['en', 'ta']

Key points:

  • The value attribute is what PHP receives — not the visible label.
  • Unchecked checkboxes, unselected radio groups, and empty multi-selects send nothing: the key is missing from $_POST.
  • Names ending in [] produce arrays.

Single Checkbox

Reading a Checkbox

<?php
// Request body: newsletter=1   (checkbox checked)
// or:           (empty)        (checkbox unchecked)

$wantsNewsletter = ($_POST['newsletter'] ?? null) === '1';

Because an unchecked checkbox is not sent, ?? null provides a default, and the strict comparison checks for the exact expected value.

The Hidden Field Technique

Sometimes you want the field to be present either way, for example when saving settings:

<input type="hidden" name="newsletter" value="0">
<input type="checkbox" name="newsletter" value="1">
  • Unchecked: only the hidden field is sent → '0'.
  • Checked: both are sent with the same name; PHP keeps the last value → '1'.

This makes "the user unchecked it" ('0') distinguishable from "the field was not part of this form" (missing).


Checkbox Groups

<label><input type="checkbox" name="courses[]" value="php"> PHP Basics</label>
<label><input type="checkbox" name="courses[]" value="mysql"> MySQL</label>
<label><input type="checkbox" name="courses[]" value="laravel"> Laravel</label>

If the user checks PHP and Laravel, PHP receives:

$_POST['courses'] = ['php', 'laravel'];

Validation must check that:

  1. The value is an array (a manipulated request could send a string).
  2. Every item is one of the allowed values.
  3. The number of selections is within any limits (at least one, at most three, …).

Radio Buttons

<label><input type="radio" name="batch" value="morning"> Morning (9–12)</label>
<label><input type="radio" name="batch" value="evening"> Evening (6–9)</label>

All radio buttons in a group share the same name, so at most one value is sent. If none is selected, the key is missing. Validation is a single allow-list check:

$batch = $_POST['batch'] ?? null;
$isValid = in_array($batch, ['morning', 'evening'], true);

Select Lists

<select name="city">
    <option value="">-- Choose a city --</option>
    <option value="MAA">Chennai</option>
    <option value="CJB">Coimbatore</option>
    <option value="IXM">Madurai</option>
</select>
  • A select always sends the value of its selected option. The placeholder option uses an empty value, so "no real choice" arrives as ''.
  • <optgroup label="Tamil Nadu"> groups options visually; it does not change what is submitted.
  • With multiple and a name ending in [], several values are sent as an array.

Defining Options in PHP

Define the options once in an array whose keys are the submitted values and whose values are the labels. The same array is then used to render the form and to validate the input:

$cities = ['MAA' => 'Chennai', 'CJB' => 'Coimbatore', 'IXM' => 'Madurai'];

$isValidCity = array_key_exists($_POST['city'] ?? '', $cities);

This guarantees that the form and the validation never disagree about which choices exist.


Practical Example: Course Registration

Validation

<?php
const COURSES = ['php' => 'PHP Basics', 'mysql' => 'MySQL', 'laravel' => 'Laravel'];
const BATCHES = ['morning' => 'Morning (9–12)', 'evening' => 'Evening (6–9)'];
const CITIES = ['MAA' => 'Chennai', 'CJB' => 'Coimbatore', 'IXM' => 'Madurai'];

function validateRegistration(array $input): array
{
    $errors = [];

    $courses = $input['courses'] ?? [];
    $courses = is_array($courses) ? array_values(array_unique(array_filter($courses, 'is_string'))) : [];

    if ($courses === []) {
        $errors['courses'] = 'Select at least one course.';
    } elseif (array_diff($courses, array_keys(COURSES)) !== []) {
        $errors['courses'] = 'Select only courses from the list.';
    }

    $batch = $input['batch'] ?? '';
    if (!is_string($batch) || !array_key_exists($batch, BATCHES)) {
        $errors['batch'] = 'Choose a batch.';
    }

    $city = $input['city'] ?? '';
    if (!is_string($city) || !array_key_exists($city, CITIES)) {
        $errors['city'] = 'Choose a city.';
    }

    $data = [
        'courses' => $courses,
        'batch' => is_string($batch) ? $batch : '',
        'city' => is_string($city) ? $city : '',
        'newsletter' => ($input['newsletter'] ?? '0') === '1',
    ];

    return [$data, $errors];
}

[$data, $errors] = validateRegistration([
    'courses' => ['php', 'python'],
    'batch' => 'night',
    'city' => 'IXM',
    'newsletter' => '1',
]);
print_r($errors);

[$data, $errors] = validateRegistration([
    'courses' => ['php', 'mysql', 'php'],
    'batch' => 'evening',
    'city' => 'MAA',
    'newsletter' => '0',
]);
var_dump($errors === []);
echo implode(', ', $data['courses']) . ' | ' . $data['batch'] . ' | ' . $data['city'] . ' | newsletter: ' . var_export($data['newsletter'], true) . "\n";

Output

Array
(
    [courses] => Select only courses from the list.
    [batch] => Choose a batch.
)
bool(true)
php, mysql | evening | MAA | newsletter: false

Step-by-Step Explanation

  1. Courses: non-array input is treated as empty, non-string items are dropped, duplicates are removed, and every remaining value must exist in COURSES. array_diff() returns the submitted values that are not allowed; any result means a manipulated or outdated value.
  2. Batch and city: each must be a string that exists as a key in its options array. The unknown batch night is rejected.
  3. Newsletter: the hidden-field technique sends '0' or '1'; only '1' counts as opting in.
  4. The function returns cleaned data (with duplicates removed) and field-keyed error messages.

Rendering With the User's Previous Choices

When the form is shown again after an error, the user's choices must stay selected. Small helpers keep the template readable:

<?php
function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function checked(bool $condition): string
{
    return $condition ? ' checked' : '';
}

function selected(bool $condition): string
{
    return $condition ? ' selected' : '';
}

$old = ['courses' => ['php', 'mysql'], 'batch' => 'evening', 'city' => 'MAA'];

const COURSES = ['php' => 'PHP Basics', 'mysql' => 'MySQL', 'laravel' => 'Laravel'];
const BATCHES = ['morning' => 'Morning (9–12)', 'evening' => 'Evening (6–9)'];
const CITIES = ['MAA' => 'Chennai', 'CJB' => 'Coimbatore', 'IXM' => 'Madurai'];

foreach (COURSES as $value => $label) {
    printf("<label><input type=\"checkbox\" name=\"courses[]\" value=\"%s\"%s> %s</label>\n",
        e($value), checked(in_array($value, $old['courses'], true)), e($label));
}

foreach (BATCHES as $value => $label) {
    printf("<label><input type=\"radio\" name=\"batch\" value=\"%s\"%s> %s</label>\n",
        e($value), checked($value === $old['batch']), e($label));
}

echo "<select name=\"city\">\n";
echo "<option value=\"\">-- Choose a city --</option>\n";
foreach (CITIES as $value => $label) {
    printf("<option value=\"%s\"%s>%s</option>\n", e($value), selected($value === $old['city']), e($label));
}
echo "</select>\n";

Output (HTML)

<label><input type="checkbox" name="courses[]" value="php" checked> PHP Basics</label>
<label><input type="checkbox" name="courses[]" value="mysql" checked> MySQL</label>
<label><input type="checkbox" name="courses[]" value="laravel"> Laravel</label>
<label><input type="radio" name="batch" value="morning"> Morning (9–12)</label>
<label><input type="radio" name="batch" value="evening" checked> Evening (6–9)</label>
<select name="city">
<option value="">-- Choose a city --</option>
<option value="MAA" selected>Chennai</option>
<option value="CJB">Coimbatore</option>
<option value="IXM">Madurai</option>
</select>

How It Works

  • Each control is generated from the same option arrays used for validation.
  • checked and selected are added only where the previous value matches, using strict comparison so that, for example, the value '0' is not confused with an empty selection.
  • Values and labels are escaped, even though they come from your own code — a consistent habit prevents mistakes when options later come from a database.

Keeping previous input in forms is covered further in Sticky Forms.


Common Mistakes

Reading Unchecked Fields Without Defaults

Effect: "Undefined array key" warnings.

Fix: $_POST['field'] ?? null (or ?? [] for groups).

Forgetting [] in Group Names

Effect: Only the last checked value is received.

Fix: Name checkbox groups and multi-selects name="field[]".

Trusting Submitted Choices

Effect: Users submit values that were never offered (other prices, roles, or IDs).

Fix: Validate every choice against the options array.

Comparing With the Label Instead of the Value

Effect: Validation fails, or labels change break the logic.

Fix: Use stable value codes; labels are for display only.

Loose Comparisons When Re-Selecting

Effect: Wrong options appear selected (for example, 0 == '' in older code).

Fix: Use === and in_array(..., true).


Best Practices

  • Define options once (value ⇒ label) and use them for both rendering and validation.
  • Use [] names for multi-value inputs, and check that the received value is an array.
  • Validate every submitted choice with allow-lists.
  • Use the hidden-field technique when an unchecked box must be stored explicitly.
  • Re-check and re-select the user's choices when redisplaying the form.

Official reference: https://www.php.net/manual/en/faq.html.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

Ask questions about Checkbox, Radio and Select Inputs and get answers drawn from it.

Signed-in readers only.