Skip to content

PHP Tutorial Forms and User Input

Handling Empty Values

Lesson 141 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

“Empty” has several meanings in PHP. Choose the check that matches the question you are asking.

QuestionUse
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

index.php
PHP
<?php
$quantity = "0";

var_dump(empty($quantity));
var_dump(trim($quantity) === "");
Output
OUTPUT
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.

index.php
PHP
<?php
$_POST = ["name" => "Isha", "phone" => "   "];

$phone = trim($_POST["phone"] ?? "");
$phone = $phone === "" ? null : $phone;

var_dump($phone);
Output
OUTPUT
NULL

A default for a missing value

index.php
PHP
<?php
$_POST = [];

$sort = $_POST["sort"] ?? "newest";

echo $sort;
Output
OUTPUT
newest

Blank vs missing vs zero

index.php
PHP
<?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";
}
Output
OUTPUT
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.

index.php
PHP
<?php
$_POST = [];

$agree = isset($_POST["agree"]);

var_dump($agree);
Output
OUTPUT
bool(false)

Numbers

For numeric input, validate with filter_var() and compare with === false, so that 0 stays valid.

index.php
PHP
<?php
$value = filter_var("0", FILTER_VALIDATE_INT);

var_dump($value !== false);
Output
OUTPUT
bool(true)
lightbulb
One helper
Put your “is this blank?” rule in one small function and reuse it. Then every field in the project treats "0", spaces and missing keys the same way.