isset() returns true when a variable exists and its value is not null. It can also check nested array keys safely without producing an undefined-key warning.
<?php
$user = ['name' => 'Asha'];
if (isset($user['name'])) {
echo $user['name'];
}
?>
<?php
$x="some value"; // assigned a string to the variable $x here
if(isset($x)){ // checking the existence of the variable by isset
echo "The variable exists";
}else{
echo " Variable does not exists ";
}
?>
Output
The variable exists
Some time we have to check the existence of a variable before using it for
our further processing. The return value will be either true or false.
<?php
$test_var=null;
if(isset($test_var)){echo " Output : True";}
else{
echo "Output : False ";
}?>
Output is
Output : False
$test_var='';
The output will change to
Output : True
<?php
$test_var1='';
$test_var2='';
unset($test_var2);
if(isset($test_var1,$test_var2)){echo " Output : True";}
else{
echo "Output : False ";
}
?>
By using unset() function we have removed one variable hence the output of isset function will be FALSE
<?php
$my_array=array("first"=>'test', "second"=>34, "third"=>'');
var_dump(isset($my_array['first'])); // bool(true)
var_dump(isset($my_array['second'])); // bool(true)
var_dump(isset($my_array['new_one'])); // bool(false)
?>
$input=array('One' =>1,'Two'=>null);
echo var_dump(isset($input['Two'])); // bool(false)
If the element is equal to NULL then output became False, however array_key_exists() returns True.
$input=array('One' =>1,'Two'=>null);
if(array_key_exists('Two',$input)){ // True
echo "Key is available "; // this is the output
}else{
echo "Key is NOT available ";
}
echo "<br>";
////
echo var_dump(isset($input['Two'])); // bool(false)
if(isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
echo " session is available, Welcome $_SESSION[userid] ";
}else{
echo " No Session , Please Login ";
exit;
}
| Chris Kavanagh | 10-02-2012 |
| Very Nice Explanation. This really cleared it up for me. Thank You. | |
| masroor javed | 30-04-2013 |
| thnks for help,,,,, | |
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Chris Kavanagh | 10-02-2012 |
| Very Nice Explanation. This really cleared it up for me. Thank You. | |
| masroor javed | 30-04-2013 |
| thnks for help,,,,, | |