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';
}
data empty functions isset validation