Checking required fields in PHP confirms that users supplied non-empty values for mandatory inputs like name, email, or password before processing the form. Writing accurate required checks avoids common PHP pitfalls where valid values such as "0" are mistakenly rejected.
empty() Fails on "0"Many tutorials use empty($_POST['field']) to check required inputs, which introduces a subtle bug. In PHP, empty("0") returns true, meaning a user typing 0 for "number of dependents" fails a required check.
<?php
declare(strict_types=1);
function isBlank(mixed $value): bool
{
if ($value === null) {
return true;
}
if (is_array($value)) {
return count($value) === 0;
}
return trim((string) $value) === '';
}
$errors = [];
$payload = ['full_name' => ' ', 'dependents' => '0', 'email' => '[email protected]'];
$requiredFields = [
'full_name' => 'Full name is required.',
'dependents' => 'Number of dependents is required.',
'email' => 'Email address is required.',
];
foreach ($requiredFields as $field => $message) {
if (isBlank($payload[$field] ?? null)) {
$errors[$field] = $message;
}
}
print_r($errors);
Notice how "0" passes isBlank() cleanly while " " is flagged as missing. That single helper prevents hours of frustrating form debugging.
Add aria-invalid="true" and render a specific error message right below each invalid field. Never clear valid fields when another field fails; repopulate inputs with escaped submitted values so users do not have to retype everything.
<?php
$nameValue = htmlspecialchars((string) ($payload['full_name'] ?? ''), ENT_QUOTES, 'UTF-8');
$nameError = $errors['full_name'] ?? '';
?>
<div class="field">
<label for="full_name">Full Name *</label>
<input id="full_name" name="full_name" type="text" value="<?= $nameValue ?>" required>
<?php if ($nameError !== ''): ?>
<p class="error"><?= htmlspecialchars($nameError, ENT_QUOTES, 'UTF-8') ?></p>
<?php endif; ?>
</div>
required: Anyone can remove the required attribute in browser DevTools or send a direct curl POST request.isset($_POST['name']) alone: An empty input submits name="", so isset() returns true even though the user typed nothing.$_POST at all, and multi-selects arrive as arrays.isset() and !isBlank() for forms?isset() only checks if a key exists and is not null. Trimming and comparing against '' verifies the user actually entered visible characters.
Check both isset($_FILES['avatar']) and $_FILES['avatar']['error'] === UPLOAD_ERR_OK rather than inspecting $_POST.
Yes. Specific field errors like "Email address is required" help users and screen readers locate the exact input to fix.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.