Yogesh Chauhan's Blog

Check whether a variable exists and not empty in PHP

in PHP on July 19, 2021

These functions are useful when you want to perform a data validation whether in PHP or WordPress.


isset() determines if a variable exists.

Things to remember

  • It actually checks if the declared variable is declared and is everything else but null.
  • isset will return false if you check against a variable with null value.
    • A null character (“\0”) is not same as the PHP null constant.
  • If you pass multiple variables in isset() then all of those variables need to exist to get “true” in return. If one of them doesn’t exist, it will return false.


$a = "test";
$b = "anothertest";

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 elements in arrays

$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() function checks whether a variable is empty.

Things to remember

  • It will return true if the variable doesn’t exist or the value is equal to false.
  • If empty() returns true, it doesn’t always mean that the variable doesn’t exist.


$var = 0;

// Evaluates to 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’ll return true.

$var = 0;

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

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Order By and Group By in PostgresPostgresEverything you need to know about ANY, SOME and ALL Operators in PostgresPostgresHow to create a secure random number using JavaScript?JavaScriptHow to create a Bootstrap style accordion using CSS and JavaScript?CSSSimple Page Hit Counter in PHPPHPSocial Media Colors: LESS VariablesMiscellaneous