Variable handling 函数
在线手册:中文 英文
PHP手册

isset

(PHP 4, PHP 5)

isset检测变量是否设置

说明

bool isset ( mixed $var [, mixed $var [, $... ]] )

如果 var 存在则返回 TRUE,否则返回 FALSE

如果已经使用 unset() 释放了一个变量之后,它将不再是 isset()。若使用 isset() 测试一个被设置成 NULL 的变量,将返回 FALSE。同时要注意的是一个 NULL 字节("\0")并不等同于 PHP 的 NULL 常数。

Note: 警告

isset() 只能用于变量,因为传递任何其它参数都将造成解析错误。若想检测常量是否已设置,可使用 defined() 函数。

<?php

$var 
'';

// 结果为 TRUE,所以后边的文本将被打印出来。
if (isset($var)) {
    print 
"This var is set set so I will print.";
}

// 在后边的例子中,我们将使用 var_dump 输出 isset() 的返回值。

$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

?>

这对于数组中的元素也同样有效:

<?php

$a 
= array ('test' => 1'hello' => NULL);

var_dump( isset ($a['test']) );            // TRUE
var_dump( isset ($a['foo']) );             // FALSE
var_dump( isset ($a['hello']) );           // FALSE

// 键 'hello' 的值等于 NULL,所以被认为是未置值的。
// 如果想检测 NULL 键值,可以试试下边的方法。 
var_dumparray_key_exists('hello'$a) ); // TRUE

?>

Note: 因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。

参见 empty()unset()defined()array_key_exists() 和错误控制 @ 运算符。

参数

var

The variable to be checked.

...

Another variable ...

返回值

Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

更新日志

版本 说明
5.4.0

Checking non-numeric offsets of strings now returns FALSE.

范例

Example #1 isset() Examples

<?php

$var 
'';

// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
    echo 
"This var is set so I will print.";
}

// In the next examples we'll use var_dump to output
// the return value of isset().

$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

?>

This also work for elements in arrays:

<?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

?>

Example #2 isset() on String Offsets

PHP 5.4 changes how isset() behaves when passed string offsets.

<?php
$expected_array_got_string 
'somestring';
var_dump(isset($expected_array_got_string['some_key']));
var_dump(isset($expected_array_got_string[0]));
var_dump(isset($expected_array_got_string['0']));
var_dump(isset($expected_array_got_string[0.5]));
var_dump(isset($expected_array_got_string['0.5']));
var_dump(isset($expected_array_got_string['0 Mostel']));
?>

以上例程在PHP 5.3中的输出:

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

以上例程在PHP 5.4中的输出:

bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)

注释

Warning

isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.

Note: 因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。

Note:

When using isset() on inaccessible object properties, the __isset() overloading method will be called, if declared.

参见


Variable handling 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 检测变量是否设置

用户评论:

zango24 at yahoo dot com (31-Mar-2012 12:38)

For my wordpress blog, I have a front end form for posting on my site, which offcourse use PhP. The form is similar to what mentioned in this tutorial: http://voodoopress.com/review-of-posting-from-front-end-form/

However, as you all know open forms are spambots baits. Lately, I have seen some spambot positings on my site through this form. I looked around for a solution but found that "HoneyPot captcha" could be a possible solution. The only problems here are I hv limited coding understanding.

I found the codes for HoneyPot captcha in this tutorial: http://devgrow.com/simple-php-honey-pot/

I dont know in "which place" and "what code" I should add to make a functional FrontEnd posting form completed with HoneyPot Captcha. Thanks for early help. Zan

david at thegallagher dot net (09-Mar-2012 10:20)

Just to reiterate on what everyone has already said before, you should not use wrapper functions for isset. Using a wrapper function will generate a Notice unless you pass the unset variable by reference, in which case it is the equivalent to writing using $var === null (which is a lot faster). Even if you do pass the variable by reference, you could still get notices using multidimensional arrays where isset() would silently return false.

qeremy (07-Mar-2012 11:36)

Simple solution for: "Fatal error: Can't use function return value in write context in ..."

<?php
function _isset($val) { return isset($val); }
?>

Dr. McKay (09-Feb-2012 01:18)

It's worth noting that if a GET variable is passed without a variable, isset will return true on it.

http://www.example.com/?somevar

<?php
if(isset($_GET['somevar'])) {
   
// this is true and will be executed
}
?>

dfugi9488 at yahoo dot com (08-Jan-2012 03:56)

it is also worth noting that isset() will return FALSE when its argument is a class attribute that is simply defined with no value given. e.g.

<?php

class Test
{
    public static
$set;
   
    public static function
setTest() {
        if(!isset(
self::$set)) {
            return
"not set";
        }else {
            return
"set";
        }
    }
}

echo
Test::setTest(); //returns "not set"

?>

john at darven dot co dot uk (14-Nov-2011 10:37)

It is worth noting that in order to check for the existence of a key within an array, regardless of it's contents one should use array_key_exists() not isset(). 

isset() will (correctly) return false if the value of your array key is null, which may be a perfectly valid condition.

gonchalox at gmail dot com (25-Jun-2011 12:33)

Useful to check if the variable have some value...specially for GET POST variables

<?php
function isset_or(&$check, $alternate = NULL)
{
    return (isset(
$check)) ? (empty($check) ? $alternate : $check) : $alternate;
}

function
getGETPOST($var)
{
      return
isset_or($_GET[$var],isset_or($_POST[$var],"Empty"));
}
?>

Example
echo getGETPOST('na'); //Find the na varriabl by get and post

benallfree at gmail dot com (22-Apr-2011 02:21)

isset() returns TRUE if a value is NULL. That seems wrong to me as there is no way to distinguish between a value set to NULL and a truly undefined value.

If you have this problem inside a class, there is a fix:

<?php
class T
{
  function
__isset($att)
  {
   
$props = get_object_vars($this);
    return
array_key_exists($att, $props);
  }
}

$x = new T();
$x->foo_exists = 4;

var_dump(isset($x->foo_exists)); // TRUE
var_dump(isset($x->bar_exists)); // FALSE
?>
[EDITOR thiago NOTE: This snippet has improvements by "Paul Lashbrook"]

Cuong Huy To (23-Mar-2011 01:08)

1) Note that isset($var) doesn't distinguish the two cases when $var is undefined, or is null. Evidence is in the following code.

<?php
unset($undefined);
$null = null;
if (
true === isset($undefined)){echo 'isset($undefined) === true'} else {echo 'isset($undefined) === false'); // 'isset($undefined) === false'
if (true === isset($null)){echo 'isset($null) === true'} else {echo 'isset($null) === false');              // 'isset($null)      === false'
?>

2) If you want to distinguish undefined variable with a defined variable with a null value, then use array_key_exist

<?php
unset($undefined);
$null = null;

if (
true !== array_key_exists('undefined', get_defined_vars())) {echo '$undefined does not exist';} else {echo '$undefined exists';} // '$undefined does not exist'
if (true === array_key_exists('null', get_defined_vars())) {echo '$null exists';} else {echo '$null does not exist';}                // '$null exists'
?>

francois vespa (23-Dec-2010 03:21)

Now this is how to achieve the same effect (ie, having isset() returning true even if variable has been set to null) for objects and arrays

<?php

// array

$array=array('foo'=>null);

return isset(
$array['foo']) || array_key_exists('foo',$array)
  ?
true : false ; // return true

return isset($array['inexistent']) || array_key_exists('inexistent',$array)
  ?
true : false ; // return false

// static class

class bar

{
  static
$foo=null;
}

return isset(
bar::$foo) || array_key_exists('foo',get_class_vars('bar'))
  ?
true : false ; // return true

return isset(bar::$inexistent) || array_key_exists('inexistent',get_class_vars('bar'))
  ?
true : false ; // return false

// object

class bar
{
    public
$foo=null;
}

$bar=new bar();

return isset(
$bar->foo) || array_key_exists('foo',get_object_vars($bar))
  ?
true : false ; // return true

return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
  ?
true : false ; // return true

// stdClass

$bar=new stdClass;
$bar->foo=null;

return isset(
$bar->foo) || array_key_exists('foo',get_object_vars($bar))
  ?
true : false ; // return true

return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
  ?
true : false ; // return true

?>

Raphael Campos (06-Jul-2010 12:10)

Keep in mind that an empty string is not null, and an empty GET or POST field returns an empty string instead of NULL, thus...

file.php?foo

<?php
$a
= '';
$b = NULL;

isset(
$a); // => TRUE
isset($b); // => FALSE
(isset($a) && $a === ''); // => TRUE
?>

With that in mind, one probably would use isset() to check if a variable has been declared somehow and it's value is not the special value NULL. If you want to check if the value is an empty string, it's probably a better idea to check it literally:

<?php
(isset($a) && $a == '') // => TRUE
?>

i [at] nemoden [dot] com (15-Jun-2010 07:48)

Simple, but very useful:

<?php
function issetOr($var, $or = false) {
  return isset(
$var) ? $var : $or;
}
?>

Some examples:
<?php
$a
= '1';
$b = '2';
echo
issetOr($a,issetOr($b,3)); // 1
?>
<?php
$b
= '2';
echo
issetOr($a,issetOr($b,3)); // 2
?>
<?php
echo issetOr($a,issetOr($b,3)); // 3
?>

senthil sent222 at gmail dot com (26-May-2010 03:14)

just as note: if you want to check isset() with string variables
<?php
$var
='string value';
if(isset(
$var['somekey']){          //it will be treated as true
echo 'This will be printed';
}
?>

mohd at bahrain dot bz (10-Jan-2010 12:02)

HTML table to displays how different variables are evaluated ..
<?php
$TEST_VAR
= array(
'|NULL' => NULL,
'|"NULL"' => "NULL",
'|false' => false,
'|true' => true,
'|FALSE' => FALSE,
'|TRUE' => TRUE,
'|"false"' => "false",
'|"true"' => "true",
'|0' => 0,
'|1' => 1,
'|"0"' => "0",
'|"1"' => "1",
'|NotExsist' => $notexist,
'|""' => "",
'|array()' => array(),
'|array("A", "B")' => array("A", "B"),
'|$_GET' => $_GET,
'|$_POST' => $_POST,
'|count($_GET)' => count($_GET),
'|count($_POST)' => count($_POST),
'|1.5' => 1.5,
'|1e7' => 1e7,
'|-14' => -14,
'|005' => 005,
'|(object) "Halo"' => (object) "Halo",
'|fopen("php://stdin")' => fopen("php://stdin", "r")
);
$CASE = array(
'$var != ""',
'!isset($var)',
'!is_null($var)',
'$var != NULL',
'$var !== NULL',
'!empty($var)',
'$var != true',
'$var !== true',
'$var != false',
'$var !== false',
'!is_bool($var)',
'!is_numeric($var)',
'!is_int($var)',
'!is_float($var)',
'!is_array($var)',
'!is_object($var)',
'!is_resource($var)',
);

$T = 'TRUE'; $F = 'FALSE';

/* CSS */
$lf = "\r\n"; $ds = "  "; $gt = '>'; $q = '"'; $ac = ' align="center"';
$t = ' style='; $b = 'background-'; $c = 'color:'; $c1 = $t.$q.$b.$c.'#EBEBEB'.$q;
$w = 'white-space:nowrap;';
$br = '<br />'; $s1 = '<span'; $s2 = '</span>';
$T = $s1.$t.$q.$c.'#0000FF'.$q.$gt.$T.$s2; $F = $s1.$t.$q.$c.'#FF0000'.$q.$gt.$F.$s2;
$t1 = '<table border="1" cellspacing="2" cellpadding="5"'.$t.$q;
$t1 .= 'font-weight:bold; font-size:9px; font-family:Tahoma,Arial;'.$q.$gt;
$t2 = '</table>'; $r1 = '<tr'; $r2 = '</tr>'; $d1 = '<td'; $d2 = '</td>';

$K = array_keys($TEST_VAR); $n = count($K); $m = count($CASE);

$da = $ds.$ds.$d1.$ac.$gt;
$dz = $d2.$lf;

echo
$t1.$lf;

$v = 14;
for (
$i=0; $i<$n; $i++) {
if ( (
$i != ($n-1)) && ($v > 13) ) {
    echo
$ds.$r1.$t.$q.$b.$c.'#CCCCCC'.$q.$gt.$lf;
    echo
$ds.$ds.$d1.$ac.$gt
   
.'$VAR/IF NOT'
   
.$dz;
    for (
$j=0; $j<$m; $j++) {
        echo
$ds.$ds.$d1.$ac.$t.$q.$w.$q.$gt
       
.htmlspecialchars($CASE[$j],ENT_QUOTES)
        .
$dz;   
    }
    echo
$ds.$ds.$d1.$ac.$gt
   
.'$VAR/IF NOT'
   
.$dz;
    echo
$ds.$r2.$lf;
   
$v = 0;
}
$v += 1;

echo
$ds.$r1.(($ch=(($ch)?false:true))?'':$c1).$gt.$lf;

echo
$ds.$ds.$d1.$ac.$t.$q.$w.$q.$gt
.(htmlspecialchars(trim($K[$i],"|"),ENT_QUOTES))
.
$dz;

/* ($var != "")? */
echo $da
.(( $TEST_VAR[($K[$i])] != "" ) ? $T:$F)
.
$dz;
/* (!isset($var))? */
echo $da
.(( !isset($TEST_VAR[($K[$i])]) ) ? $T:$F)
.
$dz;
/* (!is_null($var))? */
echo $da
.(( !is_null($TEST_VAR[($K[$i])]) ) ? $T:$F)
.
$dz;
/* ($var != NULL)? */
echo $da
.(( $TEST_VAR[($K[$i])] != NULL ) ? $T:$F)
.
$dz;
/* ($var !== NULL)? */
echo $da
.(( $TEST_VAR[($K[$i])] !== NULL ) ? $T:$F)
.
$dz;
/* (!empty($var))? */
echo $da
.(( !empty($TEST_VAR[($K[$i])]) ) ? $T:$F)
.
$dz;
/* ($var != true)? */
echo $da
.(( $TEST_VAR[($K[$i])] != true ) ? $T:$F)
.
$dz;
/* ($var !== true)? */
echo $da
.(( $TEST_VAR[($K[$i])] !== true ) ? $T:$F)
.
$dz;
/* ($var != false)? */
echo $da
.(( $TEST_VAR[($K[$i])] != false ) ? $T:$F)
.
$dz;
/* ($var !== false)? */
echo $da
.(( $TEST_VAR[($K[$i])] !== false ) ? $T:$F)
.
$dz;
/* (!is_bool($var))? */
echo $da
.(( !is_bool($TEST_VAR[($K[$i])]) ) ? $T:$F)
.
$dz;
/* (!is_numeric($var))? */
echo $da
.(( !is_numeric($TEST_VAR[($K[$i])]) ) ? $T:$F)
.
$dz;
/* (!is_int($var))? */
echo $da
.(( !is_int($TEST_VAR[($K[$i])]) ) ? $T:$F)
.
$dz;
/* (!is_float($var))? */
echo $da
.(( !is_float($TEST_VAR[($K[$i])]) ) ? $T:$F)
.
$dz;
/* (!is_array($var))? */
echo $da
.(( !is_array($TEST_VAR[($K[$i])]) ) ? $T:$F)
.
$dz;
/* (!is_object($var))? */
echo $da
.(( !is_object($TEST_VAR[($K[$i])]) ) ? $T:$F)
.
$dz;
/* (!is_resource($var))? */
echo $da
.(( !is_resource($TEST_VAR[($K[$i])]) ) ? $T:$F)
.
$dz;
echo
$ds.$ds.$d1.$ac.$t.$q.$w.$q.$gt
.(htmlspecialchars(trim(trim($K[$i],"|")),ENT_QUOTES))
.
$dz;

echo
$ds.$r2.$lf;

}
echo
$t2.$lf;
@
fclose($file_handle);

function
n0t($var=false) {
    return (( (!isset(
$var)) || ((!$var) && ($var !== "0")) )? true: false);
}
?>

Robert dot VanDell at cbs dot com (08-Jan-2010 10:19)

Here's a nice little function that I use everywhere that'll help with setting alternate values so you don't have a bunch of situations like:

<?php
if(isset($a))
{
   
$b = $a;
}
else
{
   
$b = "default";
}

function
isset_or(&$check, $alternate = NULL)
{
    return (isset(
$check)) ? $check : $alternate;
}

// Example usage:
$first_name = isset_or($_POST['first_name'], "Empty");
$total        = isset_or($row['total'], 0);

?>

Anl zselgin (14-Aug-2009 11:30)

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

So why it is under "Variable handling Functions". Maybe there should be some good documentation field for language constructs.

alexander dot holmback at gmail dot com (23-Mar-2009 10:48)

<?php
$abc
= 'test';
?>

$abc is not an array, but you can use the brackets to reach a single byte in the string using numbers.

<?php
$abc
[0] = 't'        //first letter in 'test'
$abc[1] = 'e'        //second letter in 'test'
$abc[2] = 's'        //third letter in 'test'
$abc[3] = 't'        //fourth letter in 'test'
?>

When using $abc['astring'], php will cast any string to 0 (see type juggling) which result in the letter 't' which indeed is set.

isset($abc['astring'] = isset($abc[0]) = true.

yarco dot w at gmail dot com (18-Mar-2009 08:30)

just following what edsko said, it is very amazing when you use isset to check a string. look at what i found:

[yarco@localhost ~]$ php -a
Interactive shell

php > $abc = 'test';
php > print isset($abc['e']) ? 'yes' : 'no';
yes
php > print isset($abc['d']) ? 'yes' : 'no';
yes
php > print isset($abc['aaaaaaa']) ? 'yes' : 'no';
yes
php > print isset($abc[23]) ? 'yes' : 'no';
no

If you use string as index, isset would always return true.
(but i don't think it should return true)

Ashus (08-Dec-2008 09:05)

Note that array keys are case sensitive.

<?php
$ar
['w'] = true;

var_dump(isset($ar['w']),
      isset(
$ar['W']));
?>

will report:
bool(true) bool(false)

jwvdveer at gmail dot com (10-Nov-2008 06:29)

Here a short note on the function tomek wrote:
Don't use it, because it is still better to use !$var than !is($var).

Some comments on the body of the function:
<?php
function is($var)
{
if (!isset(
$var)) return false; # Variable is always set... Otherwise PHP would have thrown an error on call.
if ($var!==false) return true; # So, 0, NULL, and some other values may not behave like isNot? And what about the difference between a class and NULL?
return false;
}
?>

The reason why you shall not use this function:
Notice: Undefined variable: {variablename} in {file} on line {__LINE__}

It's me as plain as the nose on your face that the piece of code hasn't been tested with E_NOTICE.

So my advice in this case is: don't use the above function, but simply use !, and functions such like is_null in the situation they are made for.

tomek (26-Oct-2008 02:48)

Here's a simple function to test if the variable is set:

<?php
function is($var)
{
if (!isset(
$var)) return false;
if (
$var!==false) return true;
return
false;
}
?>

Now instead of very popular (but invalid in many situations):

if (!$var) $var=5;

you can write:

if (!is($var)) $var=5;

a dot schaffhirt at sedna-soft dot de (12-Oct-2008 04:01)

You can safely use isset to check properties and subproperties of objects directly. So instead of writing

    isset($abc) && isset($abc->def) && isset($abc->def->ghi)

or in a shorter form

    isset($abc, $abc->def, $abc->def->ghi)

you can just write

    isset ($abc->def->ghi)

without raising any errors, warnings or notices.

Examples
<?php
    $abc
= (object) array("def" => 123);
   
var_dump(isset($abc));                // bool(true)
   
var_dump(isset($abc->def));           // bool(true)
   
var_dump(isset($abc->def->ghi));      // bool(false)
   
var_dump(isset($abc->def->ghi->jkl)); // bool(false)
   
var_dump(isset($def));                // bool(false)
   
var_dump(isset($def->ghi));           // bool(false)
   
var_dump(isset($def->ghi->jkl));      // bool(false)

   
var_dump($abc);                       // object(stdClass)#1 (1) { ["def"] => int(123) }
   
var_dump($abc->def);                  // int(123)
   
var_dump($abc->def->ghi);             // null / E_NOTICE: Trying to get property of non-object
   
var_dump($abc->def->ghi->jkl);        // null / E_NOTICE: Trying to get property of non-object
   
var_dump($def);                       // null / E_NOTICE: Trying to get property of non-object
   
var_dump($def->ghi);                  // null / E_NOTICE: Trying to get property of non-object
   
var_dump($def->ghi->jkl);             // null / E_NOTICE: Trying to get property of non-object
?>

edsko (05-Oct-2008 12:13)

It has been remarked by various people that isset is the opposite of is_null "in all but buggy cases". This is not true:

<?php
  $str
= "hi";
 
var_dump(isset($str[1]));
 
var_dump(@!is_null($str[1]));
 
var_dump(isset($str[2]));
 
var_dump(@!is_null($str[2]));
?>

outputs

bool(true)
bool(true)
bool(false)
bool(true)

mark dot fabrizio at gmail dot com (16-Sep-2008 03:01)

I know this is probably not the recommended way to do this, but it seems to work fine for me. Instead of the normal isset check to extract variables from arrays (like $_REQUEST), you can use the @ prefix to squelch any errors.

For example, instead of:
<?php
$test
= isset($_REQUEST['test']) ? $_REQUEST['test'] : null;
?>
you can use:
<?php
$test
= @$_REQUEST['test'];
?>

It saves some typing, but doesn't give the opportunity to provide a default value. If 'test' is not an assigned key for $_REQUEST, the assigned value will be null.

mandos78 AT mail from google (29-Jul-2008 10:40)

Careful with this function "ifsetfor" by soapergem, passing by reference means that if, like the example $_GET['id'], the argument is an array index, it will be created in the original array (with a null value), thus causing posible trouble with the following code. At least in PHP 5.

For example:

<?php
$a
= array();
print_r($a);
ifsetor($a["unsetindex"], 'default');
print_r($a);
?>

will print

Array
(
)
Array
(
    [unsetindex] =>
)

Any foreach or similar will be different before and after the call.

soapergem at gmail dot com (02-Jul-2008 09:34)

It is possible to encapsulate isset() calls inside your own functions if you pass them by reference (note the ampersand in the argument list) instead of by value. A prime example would be the heavily-requested "ifsetor" function, which will return a value when it is set, otherwise a default value that the user specifies is used.

<?php

function ifsetor(&$val, $default = null)
{
    return isset(
$val) ? $val : $default;
}

//    example usage
$id = intval(ifsetor($_GET['id'], 0));

?>

soapergem at gmail dot com (04-Jun-2008 10:19)

Below a user by the name of Scott posted an isval() function; I just wanted to point out a revision to his method since it's a bit lengthy for what it does. The trick is to realize that a boolean AND clause will terminate with false as soon as it encounters anything that evaluates to false, and will skip over any remaining checks.

Instead of taking up the space to define isval(), you could just run inline commands for each variable you need to check this:

<?php

$isval
= isset($_POST['var']) && !empty($_POST['var']);

?>

Also be warned that if you try to encapsulate this into a function, you might encounter problems. It's meant to stand alone.

John A. Bilicki III (10-Mar-2008 07:08)

I was attempting to use isset to detect if a class existed or not and kept having an error...

Call to a member function get() on a non-object...

For example I have some pages where I want to disable my own error reporting for non-existent HTTP queries. The HTTP query error handling file was merely included in my templates though now I can declare a class that uses that template system, declare an error class, and have the template system not serve the error handling when I will be using a large array of queries that I will not be tracking...
<?php if (!class_exists('error')) {include("includes.php");} ?>

anonymousleaf at gmail dot com (25-Feb-2008 06:16)

isset expects the variable sign first, so you can't add parentheses or anything.

<?php
    $foo
= 1;
    if(isset((
$foo))) { // Syntax error at isset((
       
$foo = 2;
    }
?>

muratyaman at gmail dot com (07-Feb-2008 12:40)

To organize some of the frequently used functions..

<?php

/**
 * Returns field of variable (arr[key] or obj->prop), otherwise the third parameter
 * @param array/object $arr_or_obj
 * @param string $key_or_prop
 * @param mixed $else
 */
function nz($arr_or_obj, $key_or_prop, $else){
 
$result = $else;
  if(isset(
$arr_or_obj)){
    if(
is_array($arr_or_obj){
      if(isset(
$arr_or_obj[$key_or_prop]))
       
$result = $arr_or_obj[$key_or_prop];
    }elseif(
is_object($arr_or_object))
      if(isset(
$arr_or_obj->$key_or_prop))
       
$result = $arr_or_obj->$key_or_prop;
    }
  }
  return
$result;
}

/**
 * Returns integer value using nz()
 */
function nz_int($arr_or_obj, $key_or_prop, $else){
  return
intval(nz($arr_or_obj, $key_or_prop, $else));
}

$my_id = nz_int($_REQUEST, 'id', 0);
if(
$my_id > 0){
 
//why?
}
?>

packard_bell_nec at hotmail dot com (25-Dec-2007 07:18)

Note: isset() only checks variables as anything else will result in a parse error. In other words, the following will not work: isset(trim($name)).

isset() is the opposite of is_null($var) , except that no warning is generated when the variable is not set.

sam b (13-Nov-2007 06:51)

Check out this ifsetor function. If $var is set, do nothing, otherwise $var = $default.

<?php

$name
= ifsetor($name, 'default name') ;

function
ifsetor(&$var, $default)
    {
        return isset(
$var) ? $var : $default) ;
    }
   
?>

contact at scottbyrns dot com (08-Nov-2007 01:51)

If you have for example a variable in your URL say url.php?var= and some one types in %00 the variable will pass isset. For post and get variables I wrote this function to filter out varables that are set but empty.

function isval($inp){
    if(isset($inp)){
        $len = strlen($inp);
        if($len > 0){
            return true;
        }
        else{
            return false;
        }
    }
    else{
        return false;
    }
}

petruzanauticoyahoo?com!ar (14-Oct-2007 07:22)

I've come up with a little not-so-clean but useful function to avoid checking if a variable is set before reading its value, specially useful for $_REQUEST and the like:

<?php
function toLocal( $source, &$dest, $default = null )
{
    if( isset(
$source ) )
       
$dest = $source;
    else
       
$dest = $default;
}
?>

and then call it this way:
<?php
@toLocal( $_REQUEST['item_id'], $item_id, 0 );
?>

It checks wether the variable is set, copies it to a local variable, and if it wasn't set, it assigns the new variable a default value, all in one line, preventing you to have to always check for isset() before trying to read its value.
Gotta call it with @ because if the variable is not set, then trying to pass it as an argument will yield a warning.

Petruza.

phpnotes dot 20 dot zsh at spamgourmet dot com (22-Sep-2007 10:50)

Note that isset is lazy -- the first undefined variable causes it to return. Have a look at this example:

<?php
class Foo {
    public function
__isset($varname) {
        echo
"ZOMG! isset was called on my $varname!\n";
    }
}
$foo = new Foo;
// bar will never get checked
var_dump(isset($foo->foo, $foo->bar));

// Output:
// ZOMG! isset was called on my foo!
// bool(false)
?>

codeslinger at compsalot dot com (14-Aug-2007 04:31)

The behavior of isset is complex and the results are sometimes not what people expected -- to their peril.

After dealing with isset() for awhile and peppering my code with additional checks for edge cases.  I eventually got to know and love  empty()

Most of the places that you are using isset(), empty() would do a better job.

And when you are dealing with arrays what you probably want to use instead of isset() is   array_key_exists()

These days, I almost never use isset() and I write a lot of code.

talbutt(at)mail(dot)med(dot)upenn(edu) (13-Aug-2007 04:30)

In PHP 5.2.3, really returns true if the variable is set to null.

black__ray at myway dot com (03-Jul-2007 12:40)

if(isset($_POST['in_qu']))
          {

          include("qanda/in_qu.php");
          $content.=$message;
          include("qanda/view_qanda.php");
    }
elseif(isset($_GET['rq']))
          {
          include("qanda/add_answer.php");
    }
elseif(isset($_POST['add_answer']))
          {
          include("qanda/in_an.php");
          $content.=$message;
          include("qanda/view_qanda.php");
    }
elseif($_GET['act']== 'v_qanda' && !(isset($_GET['rq'])))
{
include("qanda/view_qanda.php");
}
/*
if(isset($_POST['add_answer']))

beuc at beuc dot net (01-Jan-2007 09:56)

Beware that the chk() function below creates the variable or the array index if it didn't existed.

<?php
function chk(&$var) {
  if (!isset(
$var))
    return
NULL;
  else
    return
$var;
}

echo
'<pre>';
$a = array();
var_dump($a);
chk($a['b']);
var_dump($a);
echo
'</pre>';

// Gives:
// array
//   empty
//
// array
//   'b' => null
?>

beuc at beuc dot net (16-Dec-2006 08:35)

"empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set."

So essentially
<?php
if (isset($var) && $var)
?>
is the same as
<?php
if (!empty($var))
?>
doesn't it? :)

!empty() mimics the chk() function posted before.

roberto at spadim dot com dot br (04-Dec-2006 06:04)

test:

<?php
$qnt
=100000;
$k=array();
for (
$i=0;$i<$qnt;$i++)
$k[$i]=1;

echo
microtime()."\n";
for (
$i=0;$i<$qnt;$i++)if(isset($k[$i]));
echo
microtime()."\n";
for (
$i=0;$i<$qnt;$i++)if(array_key_exists($i,$k));
echo
microtime()."\n";
for (
$i=0;$i<$qnt;$i++)if($k[$i]==1);
echo
microtime()."\n";

?>

the interesting result:
isset is the fastest

php at bagnara dot org (29-Nov-2006 11:14)

See also property_exists() which allows detection of protected variables existing in a class even if they are NULL.

randallgirard at hotmail dot com (27-Sep-2006 07:51)

The unexpected results of isset has been really frustrating to me. Hence, it doesn't work how you'd think it would, (as documented) a var currently in the scope with a null value will return false.

Heres a quick solution, perhaps there are better ways of going about this, but heres my solution...

<?php
function is_set( $varname, $parent=null ) {
  if ( !
is_array( $parent ) && !is_object($parent) ) {
   
$parent = $GLOBALS;
  }
  return
array_key_exists( $varname, $parent );
}
?>

Hence, $varname should be a mixed value of var's to check for, and $parent can be an array or object, which will default to the GLOBAL scope. See the documentation of array_key_exists for further information.

This will allow to check if a var is in the current scope, object, or array... Whether it's a null, false, true, or any value. It depends on ARRAY_KEY_EXISTS for it's functionality which also works with Objects. Feel free to improve on this anyone ;D

DerSpezialist at Hotmail dot com (29-Aug-2006 06:09)

Note that isset() doesnt recognize $_FILES - Arrays.. additionally, i think it doesnt recognize Arrays in general at all (untested, but logical)!
Checking $_FILES will always result in Boolean FALSE i think, at least it caused my Script to calculate false Positives / Negatives... Solution: Use empty() or !empty() :-)

Tee Cee (20-Aug-2006 01:20)

In response to 10-Feb-2006 06:02, isset($v) is in all (except possibly buggy) cases equivalent to !is_null($v). And no, it doesn't actually test if a variable is set or not by my definition "$v is set if unset($v) has no effect".

<?php
unset($c); //force $c to be unset
var_dump($a=&$c); // NULL, but this actually sets $a and $c to the 'same' NULL.
var_dump(isset($c)); // bool(false)
var_dump($a = 5); // int(5)
var_dump($c); // int(5)

unset($c);
var_dump($a=&$c); // NULL
var_dump(isset($c)); // bool(false)
unset($c);
var_dump($a = 5); // int(5)
var_dump($c); // NULL
?>

In the following example, we see an alternate method of testing if a variable is actually set or not:
<?php
var_dump
(array_key_exists('c',get_defined_vars())); // false
var_dump(isset($c));                                // also false
var_dump($c);                                       // manipulate $c a bit...
var_dump((string)$c);
var_dump(print_r($c,true));
var_dump($a=$c);
var_dump(array_key_exists('c',get_defined_vars())); // ... still false
var_dump($c = NULL);                                // this sets $c
var_dump(array_key_exists('c',get_defined_vars())); // true!
var_dump(isset($c));                                // false; isset() still says it's unset
unset($c);                                          // actually unset it
var_dump(array_key_exists('c',get_defined_vars())); // false
var_dump($a=&$c);                                          
var_dump(array_key_exists('c',get_defined_vars())); // true!
unset($c);                                          // unset it again
var_dump(&$c);                                      // &NULL
var_dump(array_key_exists('c',get_defined_vars())); // true!
?>

Obviously, null values take up space (or they wouldn't show up in get_defined_vars). Also, note that &$v sets $v to NULL if it is unset.

purpleidea (17-Aug-2006 08:13)

fyi:
you *cannot* do assignments inside of the isset() function. although you *can* while inside of other functions such as is_null().

<?php
if (isset($var = $_GET['key'])) echo 'whatever'; //this will throw an error :(

if (is_null($var = $_GET['key'])) echo 'whatever'; //this will not :)
?>

hope someone finds this useful.

ludie-at-vibage-punkt-kom (16-Aug-2006 01:26)

If you don't want to bother checking every single var with isset or empty, use this function on every var you use:

<?php

function chk( & $var )
{
    if ( !isset(
$var) )
    {
        return
NULL;
    }
    else
    {
        return
$var;
    }
}

?>

It takes ANYTHING as argument, and returns the exact same thing, but without Notice if the var doesn't actually exist

(21-Jul-2006 03:08)

I tried the example posted previously by Slawek:

$foo = 'a little string';
echo isset($foo)?'yes ':'no ', isset($foo['aaaa'])?'yes ':'no ';

He got yes yes, but he didn't say what version of PHP he was using.

I tried this on PHP 5.0.5 and got:  yes no

But on PHP 4.3.5 I got:  yes yes

Apparently, PHP4 converts the the string 'aaaa' to zero and then returns the string character at that position within the string $foo, when $foo is not an array. That means you can't assume you are dealing with an array, even if you used an expression such as isset($foo['aaaa']['bbb']['cc']['d']), because it will return true also if any part is a string.

PHP5 does not do this. If $foo is a string, the index must actually be numeric (e.g. $foo[0]) for it to return the indexed character.

soywiz at php dot net (14-Apr-2006 02:12)

Sometimes you have to check if an array has some keys. To achieve it you can use "isset" like this: isset($array['key1'], $array['key2'], $array['key3'], $array['key4'])
You have to write $array all times and it is reiterative if you use same array each time.

With this simple function you can check if an array has some keys:

<?php
function isset_array() {
    if (
func_num_args() < 2) return true;
   
$args = func_get_args();
   
$array = array_shift($args);
    if (!
is_array($array)) return false;
    foreach (
$args as $n) if (!isset($array[$n])) return false;
    return
true;
}
?>

Use: isset_array($array, 'key1', 'key2', 'key3', 'key4')
First parameter has the array; following parameters has the keys you want to check.

kariedoo (09-Mar-2006 06:27)

Before:

//ask, if is set
$number = isset($_GET['number']) ? $_GET['number'] : '';
$age = isset($_GET['age']) ? $_GET['age'] : '';
$street = isset($_GET['street']) ? $_GET['street'] : '';

After: --> it's easier to read

//ask, if is set
 $parameter = array('number', 'age', 'street');
 foreach($parameter as $name)
 {
    $$name = isset($_GET[$name]) ? $_GET[$name] : '';
 }

red at iklanumum dot com (10-Feb-2006 06:02)

This could be viewed as a philosophy. I wonder why a NULL variabel is being considered FALSE rather than TRUE while in isset, because if the variable has been unset it becomes undefined but a NULL variabel is still defined although it has no value. Or, perhaps, it's based on the memory usage, if it is how about $x="" ? Is empty value use memory too? This leads me to another thinking that the isset isn't have family relationship with unset although both of it are a language construct and have 'set' word :)

Slawek Petrykowski (29-Nov-2005 11:06)

<?php
$foo
= 'a little string';
echo isset(
$foo)?'yes ':'no ', isset($foo['aaaa'])?'yes ':'no ';
>

results with unexpected values:
yes yes

Well
, it is necessary to check type of $foo first !

Peter Beckman <beckman at purplecow dot com> (21-Sep-2005 08:16)

Based on the previous post, I've found this code even more useful:

<?php
function isset_sum(&$var, $val) {
    if (isset(
$var))  $var += $val;
    else             
$var  = $val;
}
?>

Now instead of:

<?php
if (isset($foo[$bar][$baz][$fooz])) $foo[$bar][$baz][$fooz] += $count;
else                               
$foo[$bar][$baz][$fooz] = $count;
?>

No more "Undefined variable" warnings, and you save your fingers and sanity!  Thanks to the previous poster for inspiration.

(14-Sep-2005 11:41)

I don't know if you guys can use this but i find this piece of code pretty useful (for readabillity at least):

function isset_else( $&v, $r )
{
    if( isset( $v ))
        return $v;
    else
        return $r;
}

This way you can go:

$a = 4;

$c += isset_else( $a, 0 );
$c += isset_else( $b, 0 );

echo $c;

Of course, this code would work anyway, but you get the point.

onno at itmaze dot com dot au ##php==owh (12-Aug-2005 08:33)

In PHP4, the following works as expected:

if (isset($obj->thing['key'])) {
  unset($obj->thing['key']) ;
}

In PHP5 however you will get a fatal error for the unset().

The work around is:

if (is_array($obj->thing) && isset($obj->thing['key'])) {
  unset($obj->thing['key']) ;
}

richard william lee AT gmail (11-Jun-2005 07:38)

Just a note on the previous users comments. isset() should only be used for testing if the variable exists and not if the variable containes an empty "" string. empty() is designed for that.

Also, as noted previosuly !empty() is the best method for testing for set non-empty variables.

darkstar_ae at hotmail dot com (25-May-2005 09:03)

isset doesn't reliably evaluate variables with blank strings (not necessarily NULL).
i.e.
$blankvar = ""; // isset will return true on this.

This is a very common pitfall when handling HTML forms that return blank text fields to the script. You're better off doing this:

if ($var != "")
return true;
else
return false;

This more of a programming practice rather than the function's shortcomings. So if you have a habit of initializing variables you're likely to run into problems with isset() if your code or php project become very large.

Andrew Penry (11-May-2005 04:17)

The following is an example of how to test if a variable is set, whether or not it is NULL. It makes use of the fact that an unset variable will throw an E_NOTICE error, but one initialized as NULL will not.

<?php

function var_exists($var){
    if (empty(
$GLOBALS['var_exists_err'])) {
        return
true;
    } else {
        unset(
$GLOBALS['var_exists_err']);
        return
false;
    }
}

function
var_existsHandler($errno, $errstr, $errfile, $errline) {
  
$GLOBALS['var_exists_err'] = true;
}

$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (
var_exists($l)) ? "True " : "False ";
echo (
var_exists($k)) ? "True " : "False ";
restore_error_handler();

?>

Outputs:
True False

The problem is, the set_error_handler and restore_error_handler calls can not be inside the function, which means you need 2 extra lines of code every time you are testing. And if you have any E_NOTICE errors caused by other code between the set_error_handler and restore_error_handler they will not be dealt with properly. One solution:

<?php

function var_exists($var){
   if (empty(
$GLOBALS['var_exists_err'])) {
       return
true;
   } else {
       unset(
$GLOBALS['var_exists_err']);
       return
false;
   }
}

function
var_existsHandler($errno, $errstr, $errfile, $errline) {
   
$filearr = file($errfile);
    if (
strpos($filearr[$errline-1], 'var_exists') !== false) {
       
$GLOBALS['var_exists_err'] = true;
        return
true;
    } else {
        return
false;
    }
}

$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (
var_exists($l)) ? "True " : "False ";
echo (
var_exists($k)) ? "True " : "False ";
is_null($j);
restore_error_handler();

?>

Outputs:
True False
Notice: Undefined variable: j in filename.php on line 26

This will make the handler only handle var_exists, but it adds a lot of overhead. Everytime an E_NOTICE error happens, the file it originated from will be loaded into an array.

phpnet dot 5 dot reinhold2000 at t spamgourmet dot com (10-Apr-2005 04:33)

if you want to check whether the user has sent post vars from a form, it is a pain to write something like the following, since isset() does not check for zero-length strings:

if(isset($form_name) && $form_name != '') [...]

a shorter way would be this one:

if($form_name && $form_message) [...]

but this is dirty since you cannot make sure these variables exist and php will echo a warning if you refer to a non-existing variable like this. plus, a string containing "0" will evaluate to FALSE if casted to a boolean.

this function will check one or more form values if they are set and do not contain an empty string. it returns false on the first empty or non-existing post var.

<?
function postvars() {
    foreach(func_get_args() as $var) {
        if(!isset($_POST[$var]) || $_POST[$var] === '') return false;
    }
    return true;
}
?>

example: if(postvars('form_name','form_message')) [...]

yaogzhan at gmail dot com (20-Mar-2005 12:52)

in PHP5, if you have

<?PHP
class Foo
{
    protected
$data = array('bar' => null);

    function
__get($p)
    {
        if( isset(
$this->data[$p]) ) return $this->data[$p];
    }
}
?>

and
<?PHP
$foo
= new Foo;
echo isset(
$foo->bar);
?>
will always echo 'false'. because the isset() accepts VARIABLES as it parameters, but in this case, $foo->bar is NOT a VARIABLE. it is a VALUE returned from the __get() method of the class Foo. thus the isset($foo->bar) expreesion will always equal 'false'.

dubmeier aaattt Y! daht calm (01-Mar-2005 11:13)

Here are some handy wrappers to isset that I use when I need to do common evaluations like: this variable is set and has a length greater than 0, or: I want the variables value, or a blank, if not set.

/**
 * isset_echo()
 *
 * Accomplishes the following w/o warnings:
 *    echo $x;
 *    echo $x[$y];
 *    echo $x[$y][$z];
 *
 * FIXME: make this recursive so it works for N args?
 */
function isset_echo($x, $y=Null, $z=Null)
{
    if (is_array($x)) {
        if (array_key_exists($y, $x)) {
            if (is_array($x[$y])) {
                if (array_key_exists($z, $x[$y])) { echo $x[$y][$z]; }
            }
            else { echo $x[$y]; }
        }
    }
    else { echo $x; }
}

/**
 * isset_value()
 *
 * As above, but returns value instead of echoing
 */
function isset_value(&$x, $y=Null)
{
    if (is_array($x)) {
        if (array_key_exists($y, $x)) { return $x[$y]; }
    }
    else { return $x; }
}

/**
 * isset_and_equals()
 *
 * As above, but ...
 * Returns true if variable (or array member) is set and equaL to the first parameter
 */
function isset_equals($val, $w, $x=null, $y=null, $z=null) {
    if (is_array($w)) {
                if (array_key_exists($x, $w)) {
                if (is_array($w[$x])) {
                        if (array_key_exists($y, $w[$x])) {
                                    if (is_array($w[$x][$y])) {
                                        if(array_key_exists($z, $w[$x][$y])) {
                                                return ($w[$x][$y][$z] == $val) ? true : false;
                                        }
                                    } else {
                                        return ($w[$x][$y] == $val) ? true : false;
                                    }
                            }
                    } else {
                        return ($w[$x] == $val) ? true : false;
                    }
        }
    } else {
                return ($w == $val) ? true : false;
        }
}

/**
 * isset_gt0()
 *
 * As above, but returns true only if var is set and it's length is > 0
 */
function isset_gt0(&$x)
{
    if (isset($x) && strlen($x) > 0) { return true; }
    else { return false; }
}

codeslinger at compsalot dot com (07-Feb-2005 06:21)

according to the docs -- "isset() will return FALSE if testing a variable that has been set to NULL."

That statment is not always correct, sometimes isset() returns TRUE for a NULL value.  But the scenarios are obtuse.  There are a tons of bugs on this subject, all marked as bogus.

Problems occur when NULLs are in named fields of arrays and also when vars are passed by reference.

do lots of testing and code defensively.

is_null()   is your friend...

pianistsk8er at gmail dot com (10-Dec-2004 02:23)

This function is very useful while calling to the URL to specify which template to be used on certain parts of your application.

Here is an example...

<?php

    $cat
= $_GET['c'];
   
$id = $_GET['id'];   
   
$error = 'templates/error.tpl';

    if( isset(
$cat))
    {
        if( isset(
$id))
        {
           
$var = 'templates/pics/' . $cat . '-' . $id . '.tpl';
            if (
is_file($var))
            {
                include(
$var);
            }
            else
            {
                include(
$error);
            }
        }
        else
        {
           
$var = 'templates/pics/' . $cat . '.tpl';       
            if (
is_file($var))
            {
                include(
$var);
            }
            else
            {
                include(
$error);
            }
        }
    }
    else
    {
        include(
'templates/alternative.'.tpl);
    }

?>

You can see several uses of the isset function being used to specify wheter a template is to be called upon or not.  This can easily prevent other generic PHP errors.

jc dot michel at symetrie dot com (15-Nov-2004 10:35)

Using
  isset($array['key'])
is useful, but be careful!
using
  isset($array['key']['subkey'])
doesn't work as one could expect, if $array['key'] is a string it seems that 'subkey' is converted to (integer) 0 and $array['key']['subkey'] is evaluated as the first char of the string.
The solution is to use
  is_array($array['key']) && isset($array['key']['subkey'])

Here is a small code to show this:

<?php
$ex
= array('one' => 'val1','two' => 'val2');
echo
'$ex = ';print_r($ex);
echo
"<br />";

echo
" isset(\$ex['one']['three']) : ";
if (isset(
$ex['one']['three']))
    echo
'true';
else
    echo
'false';

echo
"<br />";
echo
"is_array(\$ex['one']) &&  isset(\$ex['one']['three']) : ";
if (
is_array($ex['one']) && isset($ex['one']['three']))
    echo
'true';
else
    echo
'false';
?>

shows:
$ex = Array ( [one] => val1 [two] => val2 )
isset($ex['one']['three']) : true
is_array($ex['one']) && isset($ex['one']['three']) : false

jon (07-Dec-2003 06:19)

Since PHP will check cases in order, I often end up using this bit of code:

<?php
if (isset($var) && $var) {
   
// do something
}
?>

In short, if you have error reporting on, and $var is not set, PHP will generate an error if you just have:

<?php
if ($var) { // do something }
?>

...but, as noted elsewhere, will return True if set to False in this case:
<?php
if (isset($var)) { // do something }
?>

Checking both to see if $var is set, and that it equals something other than Null or False is something I find very useful a lot of times.  If $var is not set, PHP will never execute the second part of "(isset($var) && $var)", and thus never generate an error either.

This also works very nice for setting variable as well, e.g.:
<?php
$var
= (isset($var) && $var) ? $var : 'new value';
?>

flobee at gmx dot net (08-Sep-2003 10:16)

just as note: if you want to check variables by boolean value: true or false , "isset" has a different meaning!
<?php
$var
=null;
// sample 1
if($var) {
  
// if true or another value exept "false" , "null": go on here
  
echo "1. var is true or has a value $var<br>";
} else {
   echo
"1. var is &quot;false&quot; or &quot;null&quot;<br>";
}

if(!
$var) {
  
// if false or "null": go on here
  
echo "2. var has no value $var<br>";
} else {
   echo
"2. var is &quot;false&quot; or &quot;null&quot;<br>";
}

// sample 2
$var =false;
if(isset(
$var)) {
 
// $var is false so it is set to a value and the execution goes here
  
echo "3. var has value: $var<br>";
}

$var=null;
if(!isset(
$var)) {
 
// $var is null (does not exist at this time) and the execution goes here
  
echo "4. var was not set $var<br>";
}
?>