Check if a variable exists and is not empty in PHP

Check if a variable exists and is not empty in PHP. empty, isset and other PHP functions for checking a variable.

These functions come in handy when you want to validate data, whether in PHP or WordPress.

Isset()

isset() determines whether a variable exists.

The function actually checks whether the variable is declared and whether it is anything other than null.
isset will return false if you check a variable whose value is null.
A null character ("\0") is not the same as PHP's null constant.
If you pass several variables to isset(), all of them must exist for it to return "true". If any one of them doesn't exist, it will return false.

Example

$a = "test";
$b = "autrevariable";

var_dump(isset($a));     // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a);

var_dump(isset($a));     // FALSE
var_dump(isset($a, $b)); // FALSE

$foo = NULL;
var_dump(isset($foo));   // FALSE

Isset() for array elements

$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));

var_dump(isset($a['test']));            // TRUE
var_dump(isset($a['foo']));             // FALSE
var_dump(isset($a['hello']));           // FALSE

// Checking deeper array values
var_dump(isset($a['pie']['a']));        // TRUE
var_dump(isset($a['pie']['b']));        // FALSE

empty()

The empty() function checks whether a variable is empty.

The function will return true if the variable doesn't exist or if its value equals false.
If empty() returns true, it doesn't always mean the variable doesn't exist.

Example

$var = 0;

// returns true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

If you evaluate the variable above with isset(), it will return true.

$var = 0;

// returns true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty';
}

Have a web project in mind?

Website design, e-commerce or SEO: our web agency in Paris, Besançon and Normandy can help.

Free quote

Related articles