PHP Form Required

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 113 of 256

What Is a Required Field?

In simple terms: A required field is a form field the user must fill in before the form can be accepted — such as a name, an email address, or the "I accept the terms" checkbox.

Technically: Checking a required field means verifying that the submitted value is present and not blank. What counts as "blank" depends on the field type: a text field containing only spaces, an unchecked checkbox (which is not submitted at all), a select left on its placeholder option, or a checkbox group with nothing selected.

Why Required Checks Need Care

The obvious approach — empty($_POST['name']) — has a serious flaw, and different field types behave differently when left empty. Getting this right avoids two kinds of bugs: rejecting valid input (such as the value 0) and accepting meaningless input (such as a name made only of spaces).


What Browsers Send for Empty Fields

FieldUser Leaves It EmptyWhat PHP Receives
Text, email, textareaEmpty box'' (empty string)
Text with only spaces" "' ' (not empty!)
CheckboxUncheckedKey missing from $_POST
Radio groupNothing selectedKey missing
SelectPlaceholder option chosenThe placeholder's value, usually ''
Multiple select / checkbox group (name[])Nothing selectedKey missing
File inputNo file chosen$_FILES[...]['error'] === UPLOAD_ERR_NO_FILE

A complete required check must handle missing keys, whitespace-only strings, and arrays.


Why empty() Is the Wrong Tool

empty($x) is true for missing values and for every falsy value, including the string '0':

<?php
$submissions = [
    'missing' => null,
    'empty string' => '',
    'only spaces' => '   ',
    'zero' => '0',
    'name' => 'Asha',
];

foreach ($submissions as $label => $value) {
    printf("%-13s empty(): %-5s  trim check: %s\n",
        $label,
        var_export(empty($value), true),
        var_export($value === null || trim($value) === '', true)
    );
}

Output

missing       empty(): true   trim check: true
empty string  empty(): true   trim check: true
only spaces   empty(): false  trim check: true
zero          empty(): true   trim check: false
name          empty(): false  trim check: false

empty() gets two cases wrong:

  • '0' counts as empty, so a user whose answer is "0" (number of children, apartment floor, a quantity) is told the field is required.
  • ' ' counts as filled, so a name consisting only of spaces is accepted.

The trim check treats exactly the right values as blank.


A Reliable Required Check

<?php
function isFilled(mixed $value): bool
{
    if (is_array($value)) {
        return $value !== [];
    }

    return is_string($value) && trim($value) !== '';
}

$tests = [
    'missing' => null,
    'empty string' => '',
    'only spaces' => '   ',
    'zero' => '0',
    'text' => 'Asha',
    'empty array' => [],
    'checked items' => ['php'],
];

foreach ($tests as $label => $value) {
    echo str_pad($label, 14) . (isFilled($value) ? 'filled' : 'blank') . "\n";
}

Output

missing       blank
empty string  blank
only spaces   blank
zero          filled
text          filled
empty array   blank
checked items filled
  • Strings are trimmed before checking, so whitespace-only input is blank and '0' is filled.
  • Arrays (from name[] fields) are filled when at least one item was selected.
  • Anything else — null for a missing key, or an unexpected type — is blank.

Use it as isFilled($_POST['name'] ?? null).


Required Checkboxes, Radios, and Selects

"Accept the Terms" Checkbox

<label><input type="checkbox" name="terms" value="yes"> I accept the terms</label>
$acceptedTerms = ($_POST['terms'] ?? null) === 'yes';

An unchecked checkbox is not sent, so ?? null provides the default. Comparing with the exact expected value rejects anything else.

Required Radio Group

<label><input type="radio" name="plan" value="free"> Free</label>
<label><input type="radio" name="plan" value="pro"> Pro</label>
$plan = $_POST['plan'] ?? null;
$planIsValid = in_array($plan, ['free', 'pro'], true);

A required radio group is valid only when one of the allowed values is present. This one check covers both "nothing selected" and "a manipulated value".

Required Select With a Placeholder

<select name="city">
    <option value="">-- Choose a city --</option>
    <option value="MAA">Chennai</option>
    <option value="IXM">Madurai</option>
</select>

The placeholder has an empty value, so the required check is again an allow-list check: the submitted value must be one of the real options (MAA, IXM). See Checkbox, Radio and Select Inputs.


Conditionally Required Fields

Some fields are required only in certain situations — for example, a company name and GSTIN for business accounts:

<?php
function isFilled(mixed $value): bool
{
    return is_array($value) ? $value !== [] : is_string($value) && trim($value) !== '';
}

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

    if (!isFilled($input['name'] ?? null)) {
        $errors['name'] = 'Please enter your name.';
    }

    $accountType = $input['account_type'] ?? null;

    if (!in_array($accountType, ['personal', 'business'], true)) {
        $errors['account_type'] = 'Choose an account type.';
    }

    if ($accountType === 'business') {
        if (!isFilled($input['company'] ?? null)) {
            $errors['company'] = 'Company name is required for business accounts.';
        }
        if (!isFilled($input['gstin'] ?? null)) {
            $errors['gstin'] = 'GSTIN is required for business accounts.';
        }
    }

    if (($input['terms'] ?? null) !== 'yes') {
        $errors['terms'] = 'You must accept the terms.';
    }

    return $errors;
}

print_r(checkRequired(['name' => 'Asha', 'account_type' => 'personal', 'terms' => 'yes']));

print_r(checkRequired(['name' => '   ', 'account_type' => 'business', 'company' => '']));

Output

Array
(
)
Array
(
    [name] => Please enter your name.
    [company] => Company name is required for business accounts.
    [gstin] => GSTIN is required for business accounts.
    [terms] => You must accept the terms.
)

How It Works

  1. The personal account passes: company and GSTIN are not checked because they are not required for personal accounts.
  2. For the business account, the whitespace-only name, the empty company, the missing GSTIN, and the missing terms checkbox are all reported together.
  3. The account type itself is required and restricted to allowed values in one check.

On the HTML side, JavaScript can show or hide the business fields, but the server must still decide what is required based on the submitted account type.


Marking Required Fields in HTML

<?php
$errors = ['name' => 'Please enter your name.'];
$name = '';
?>
<label for="name">Name <span aria-hidden="true">*</span></label>
<input id="name" name="name" required
       value="<?= htmlspecialchars($name) ?>"
       <?= isset($errors['name']) ? 'aria-invalid="true" aria-describedby="name-error"' : '' ?>>
<?php if (isset($errors['name'])): ?>
<p id="name-error" class="error"><?= htmlspecialchars($errors['name']) ?></p>
<?php endif; ?>

Output (HTML)

<label for="name">Name <span aria-hidden="true">*</span></label>
<input id="name" name="name" required
       value=""
       aria-invalid="true" aria-describedby="name-error">
<p id="name-error" class="error">Please enter your name.</p>
  • The required attribute gives users immediate feedback in the browser.
  • An asterisk marks required fields visually; aria-hidden stops screen readers from announcing it, because required already conveys the information.
  • aria-invalid and aria-describedby connect the error message to the field for assistive technologies.

Common Mistakes

Using empty() for Required Checks

Effect: '0' is rejected, and whitespace-only input is accepted.

Fix: Trim strings and compare with ''.

Forgetting That Unchecked Fields Are Missing

Effect: "Undefined array key" warnings.

Fix: Use ?? null for checkboxes, radios, and multi-selects.

Accepting Any Non-Empty Value for Choices

Effect: Manipulated values pass the required check.

Fix: Required choices must be in an allow-list.

Relying Only on the required Attribute

Effect: Direct requests bypass it.

Fix: Repeat every required check on the server.

Showing Only the First Missing Field

Effect: Users must submit several times.

Fix: Collect and display all errors at once.


Best Practices

  • Treat missing keys, empty strings, and whitespace-only strings as blank; treat '0' as filled.
  • Check required choices with allow-lists.
  • Handle conditionally required fields on the server based on submitted values.
  • Mark required fields clearly and connect error messages to fields accessibly.
  • Use the required attribute for convenience, never as the only check.

Official reference: https://www.php.net/manual/en/function.empty.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home 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 Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays 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 array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting 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 PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types 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 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 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 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 AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about PHP Form Required and get answers drawn from it.

Signed-in readers only.