dots Created with Sketch.
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';
}

amazon

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

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
Optional arguments, Default parameters and REST parameters in JavaScriptJavaScriptData Flows in ReactReactCrypto.getRandomValues() method in JavaScriptJavaScriptWordPress: How to print ACF repeater field values?WordPressConditional operator in JavaScript (aka ternary operator)JavaScriptUPDATE and DELETE Statements in PostgresPostgres