When Does PHP’s empty() Return True? A Complete Guide

This guide explains PHP’s built-in empty() function, detailing the exact cases where a variable is considered empty, providing clear code examples, showing expected output, and offering practical tips for using empty() in form validation while highlighting its limitations compared to isset().

php Courses
php Courses
php Courses
When Does PHP’s empty() Return True? A Complete Guide

PHP empty() function

The built‑in empty() function checks whether a variable is considered “empty” and returns a boolean value. It accepts a single argument – the variable to test – and evaluates the variable against a predefined set of empty conditions.

Conditions that make empty() return true

The value is the integer 0 or the string "0".

The value is false or null.

The value is an empty array ( array()) or an object that has no properties.

The variable has never been set (i.e., it is undefined).

Comprehensive example

<?php
$var1 = '';
$var2 = 0;
$var3 = false;
$var4 = null;
$var5 = array();
$var6; // not set

$variables = [
    'var1' => $var1,
    'var2' => $var2,
    'var3' => $var3,
    'var4' => $var4,
    'var5' => $var5,
    'var6' => $var6,
];

foreach ($variables as $name => $value) {
    echo $name . ' is empty: ' . (empty($value) ? 'true' : 'false') . "
";
}
?>

When executed, the script prints true for every variable because each satisfies one of the empty conditions listed above.

Typical use case: form input validation

<?php
if (empty($_POST['username'])) {
    echo 'Please enter a username';
} else {
    // Process the submitted username
}
?>

This pattern is common in PHP applications to ensure required fields are provided before further processing.

Important caveats

empty()

can only be applied to variables. Passing a constant, a literal, or an arbitrary expression will trigger a warning.

To test whether a variable exists without evaluating its value, use isset().

For general truthiness checks of expressions, use a standard if statement rather than empty().

Understanding these nuances helps avoid unexpected behavior when validating data or controlling program flow.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

form-validationphp-functionsemptyvariable-check
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.