The isset()
function Determine if a variable is set and is not NULL.
If a variable has been unset with unset()
, it will no longer be set. isset()
will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0")
is not equivalent to the PHP NULL constant.
If multiple parameters are supplied then isset()
will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.
if you not using isset()
the script will generated a warning, with isset()
you can prevents this.
a for example reason to use isset()
is to detect if key is inside array.
for example:
<?php
$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
// The key 'hello' equals NULL so is considered unset
// If you want to check for NULL key values then try:
var_dump(array_key_exists('hello', $a)); // TRUE
// Checking deeper array values
var_dump(isset($a['pie']['a'])); // TRUE
var_dump(isset($a['pie']['b'])); // FALSE
var_dump(isset($a['cake']['a']['b'])); // FALSE
if(!$a['hello']){ //this will display a warning: Undefined variable.
echo 'hello is not set in the array';
}
?>
The problem with your example is the operator !
in PHP is NOT
, So in the two if line's here you will get the same result but the first line will display Undefined variable warning because there is no $name
variable, the second if will do NOT
to $name
variable
<?php
if(!$name){//this will display a warning: Undefined variable.
echo 'Name is not set';
}
$name=0;
if(!$name){//check the not value of $name.
echo 'Name is true';
}
?>