TExcelTAD
Home › PHP › PHP Required Fields

PHP Required Fields

Some form fields are optional — a phone number, a company name — but others must always be filled in. This lesson shows a clean pattern for required fields: detect empty values, show an error next to each missing field, and keep what the user already typed so they only fix what is wrong.

What counts as "empty"?

PHP's empty() is tempting, but it treats the string "0" as empty. For a "number of children" field, 0 is a perfectly valid answer! Trim the value and compare it with '' instead.

Value received empty($v) trim($v) === ''
"" (nothing typed) true true
" " (only spaces) false true
"0" true false
key missing (unchecked box) true (no warning) use $in['k'] ?? '' first
php · try it yourself
<?php
$values = ['', '   ', '0', 'Hanoi'];

foreach ($values as $v) {
    printf("%-8s empty(): %-5s  blank after trim: %s\n",
        var_export($v, true),
        var_export(empty($v), true),
        var_export(trim($v) === '', true));
}
''       empty(): true   blank after trim: true
'   '    empty(): false  blank after trim: true
'0'      empty(): true   blank after trim: false
'Hanoi'  empty(): false  blank after trim: false

Marking fields as required

In the HTML, the required attribute and a visual marker such as * help the user. The <span class="error"> placeholders will hold PHP's messages:

html
<form method="post">
  <p><span class="error">* required field</span></p>
  Name: <input type="text" name="name" value="<?= htmlspecialchars($name) ?>" required>
  <span class="error">* <?= $errors['name'] ?? '' ?></span>

  Email: <input type="email" name="email" value="<?= htmlspecialchars($email) ?>" required>
  <span class="error">* <?= $errors['email'] ?? '' ?></span>

  Plan:
  <input type="radio" name="plan" value="free"> Free
  <input type="radio" name="plan" value="pro"> Pro
  <span class="error">* <?= $errors['plan'] ?? '' ?></span>

  <button>Register</button>
</form>

<?= ... ?> is the short echo tag: it prints the expression. Notice how every previously entered value goes through htmlspecialchars() before it is placed inside value="...".

A reusable required-field checker

Describe the required fields once, in an array, and loop over them. This keeps the rules in one place:

php · try it yourself
<?php
$required = [
    'name'  => 'Name',
    'email' => 'Email',
    'plan'  => 'Plan',
];

function missingFields(array $input, array $required): array
{
    $errors = [];
    foreach ($required as $key => $label) {
        $value = trim((string) ($input[$key] ?? ''));
        if ($value === '') {
            $errors[$key] = "$label is required.";
        }
    }
    return $errors;
}

// The user typed spaces for the email and chose no plan
$_POST = ['name' => 'Quang', 'email' => '   '];

$errors = missingFields($_POST, $required);
print_r($errors);
Array
(
    [email] => Email is required.
    [plan] => Plan is required.
)

Tip: Radio buttons and checkboxes that are not selected are not sent at all. That is why the checker reads $input[$key] ?? '' — the key may be missing.

Putting it together

The full flow: on GET show an empty form; on POST check required fields first, then the format of the values that are present; finally either redisplay the form or accept it.

php · try it yourself
<?php
function handle(array $post): string
{
    $errors = [];
    $name  = trim($post['name'] ?? '');
    $email = trim($post['email'] ?? '');
    $plan  = $post['plan'] ?? '';

    if ($name === '')  { $errors['name']  = 'Name is required.'; }
    if ($email === '') {
        $errors['email'] = 'Email is required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Email format is invalid.';
    }
    if (!in_array($plan, ['free', 'pro'], true)) {
        $errors['plan'] = 'Please choose a plan.';
    }

    if ($errors) {
        return "Form redisplayed:\n  " . implode("\n  ", $errors);
    }
    return "Welcome, " . htmlspecialchars($name) . "! Plan: $plan";
}

echo handle(['name' => '', 'email' => 'tam@', 'plan' => 'gold']) . PHP_EOL;
echo handle(['name' => 'Tam', 'email' => 'tam@example.test', 'plan' => 'pro']) . PHP_EOL;
Form redisplayed:
  Name is required.
  Email format is invalid.
  Please choose a plan.
Welcome, Tam! Plan: pro

Checking the plan with in_array(..., true) against a list of allowed values is important: a radio button looks restricted in the browser, but an attacker can send plan=gold or anything else.

Note: Use the strict third argument true in in_array() so that comparisons don't do surprising type juggling.

Test yourself

Why can empty($_POST['kids']) be wrong for a required numeric field?

  1. It throws an exception
  2. It treats the string "0" as empty
  3. It only works for arrays
  4. It trims the value first

A radio group named plan had no option selected. What is in $_POST?

  1. 'plan' => ''
  2. 'plan' => null
  3. 'plan' => false
  4. No plan key at all

Which short tag prints an expression inside an HTML template?

  1. <?php= $x ?>
  2. <?= $x ?>
  3. <% $x %>
  4. {{ $x }}