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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
HTML canvas methodsHTMLHow to refresh a page using PHP at regularly occurring intervals?PHPHow to catch .keypress() on body using jQuery?jQueryWhat is IPS(Intrusion Prevention System), How Does It Work and What are the Detection Types?MiscellaneousHow to create a Progress Bar using JavaScript?JavaScriptHow to Draw a Circle in HTML5 Using Canvas Tag?HTML