“Empty” has several meanings in PHP. Choose the check that matches the question you are asking.
| Question | Use |
|---|---|
| Was the key sent at all? | isset($_POST["x"]) or array_key_exists() |
| Is the text blank? | trim($value) === "" |
Is the value falsy (0, "", "0", null, [])? | empty($value) |
| Is the array empty? | $array === [] or count($array) === 0 |
The “0” trap
<?php
$quantity = "0";
var_dump(empty($quantity));
var_dump(trim($quantity) === "");
bool(true)
bool(false)
A visitor who types 0 for a quantity or an age gave a valid answer. empty() says it is empty. The comparison with "" gets it right.
Optional fields
An optional field may be missing or blank. Turn blank into null, so the rest of your code has one rule.
<?php
$_POST = ["name" => "Isha", "phone" => " "];
$phone = trim($_POST["phone"] ?? "");
$phone = $phone === "" ? null : $phone;
var_dump($phone);
NULL
A default for a missing value
<?php
$_POST = [];
$sort = $_POST["sort"] ?? "newest";
echo $sort;
newest
Blank vs missing vs zero
<?php
$tests = [
"missing" => null,
"blank" => "",
"spaces" => " ",
"zero" => "0",
"text" => "hello",
];
foreach ($tests as $label => $value) {
$blank = $value === null || trim($value) === "";
echo str_pad($label, 8) . ($blank ? "blank" : "has a value") . "\n";
}
missing blank
blank blank
spaces blank
zero has a value
text has a value
Checkboxes
An unchecked checkbox is missing from the request. Treat “missing” as false.
<?php
$_POST = [];
$agree = isset($_POST["agree"]);
var_dump($agree);
bool(false)
Numbers
For numeric input, validate with filter_var() and compare with === false, so that 0 stays valid.
<?php
$value = filter_var("0", FILTER_VALIDATE_INT);
var_dump($value !== false);
bool(true)
One helper
"0", spaces and missing keys the same way.