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()

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.

Example


$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()

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.

Example


$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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #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
How to Find the Highest (or Lowest) Number in an Array in JavaScript?JavaScriptHow to Use SQL MAX() Function with Dates?SQL/MySQLHow to position an image on top of another image using CSS?CSSHow to zoom an image inside a box on hover?CSSMiddleware in NextJSNextJSAlternate Style Sheets in CSSCSS