Does isset () function do in php?

❮ PHP Variable Handling Reference

Example

Check whether a variable is empty. Also check whether the variable is set/declared:

$a = 0;
// True because $a is set
if (isset($a)) {
  echo "Variable 'a' is set.
";
}

$b = null;
// False because $b is NULL
if (isset($b)) {
  echo "Variable 'b' is set.";
}
?>

Try it Yourself »


Definition and Usage

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL.

This function returns true if the variable exists and is not NULL, otherwise it returns false.

Note: If multiple variables are supplied, then this function will return true only if all of the variables are set.

Tip: A variable can be unset with the unset() function.


Syntax

Parameter Values

ParameterDescription
variable Required. Specifies the variable to check
... Optional. Another variable to check

Technical Details

Return Value:TRUE if variable exists and is not NULL, FALSE otherwise
Return Type:Boolean
PHP Version:4.0+
PHP Changelog:PHP 5.4: Non-numeric offsets of strings now returns FALSE

❮ PHP Variable Handling Reference


(PHP 4, PHP 5, PHP 7, PHP 8)

issetDetermine if a variable is declared and is different than null

Description

If a variable has been unset with the unset() function, it is no longer considered to be set.

isset() will return false when checking a variable that has been assigned to null. Also note that a null character ("\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 considered set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.

Parameters

var

The variable to be checked.

vars

Further variables.

Return Values

Returns true if var exists and has any value other than null. false otherwise.

Examples

Example #1 isset() Examples

$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)); // TRUEunset ($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:

$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

$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']));
?>

The above example will output:

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

Notes

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: Because this is a language construct and not a function, it cannot be called using variable functions, or named arguments.

Note:

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

See Also

  • empty() - Determine whether a variable is empty
  • __isset()
  • unset() - Unset a given variable
  • defined() - Checks whether a given named constant exists
  • the type comparison tables
  • array_key_exists() - Checks if the given key or index exists in the array
  • is_null() - Finds whether a variable is null
  • the error control @ operator

p_ignorethis_lbowers at gmail dot com

5 years ago

I, too, was dismayed to find that isset($foo) returns false if ($foo == null). Here's an (awkward) way around it.

unset($foo);
if (compact('foo') != array()) {
  do_your_thing();
}

Of course, that is very non-intuitive, long, hard-to-understand, and kludgy. Better to design your code so you don't depend on the difference between an unset variable and a variable with the value null. But "better" only because PHP has made this weird development choice.

In my thinking this was a mistake in the development of PHP. The name ("isset") should describe the function and not have the desciption be "is set AND is not null". If it was done properly a programmer could very easily do (isset($var) || is_null($var)) if they wanted to check for this!

A variable set to null is a different state than a variable not set - there should be some easy way to differentiate. Just my (pointless) $0.02.

kurdtpage at gmail dot com

5 years ago

The new (as of PHP7) 'null coalesce operator' allows shorthand isset. You can use it like so:

// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Quoted from http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

a dot schaffhirt at sedna-soft dot de

13 years ago

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

beuc at beuc dot net

15 years ago

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

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

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

yaogzhan at gmail dot com

17 years ago

If you have

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

    function

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

and
$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'.

ayyappan dot ashok at gmail dot com

6 years ago

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

$a=NULL;
$b=FALSE; //The out put was TRUE.
$c=TRUE;
$d='';
$e="";
if(isset(
$b)):
echo
"TRUE";
else:
echo
"FALSE";   
endif;
?>
Could any one explain me in clarity.

mandos78 AT mail from google

14 years ago

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:

$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.

Cuong Huy To

11 years ago

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

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

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

soywiz at php dot net

16 years ago

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:

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.

andreasonny83 at gmail dot com

7 years ago

Here is an example with multiple parameters supplied

$var = array();
$var['val1'] = 'test';
$var['val2'] = 'on';

if ( isset(

$var['val1'], $var['val2'] ) && $var['val2'] === 'on' ) {
    unset(
$var['val1'] );
}
print_r( $var );
?>

This will output:
Array
(
    [val2] => on
)

The following code does the same calling "isset" 2 times:

$var = array();
$var['val1'] = 'test';
$var['val2'] = 'on';

if ( isset(

$var['val1'] ) && isset( $var['val2'] ) && $var['val2'] === 'on' ) {
    unset(
$var['val1'] );
}
print_r( $var );
?>

francois vespa

11 years ago

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

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

return isset(

$array['foo']) || array_key_exists('foo',$array)
  ?
true : false ; // return truereturn 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 truereturn 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 truereturn 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 truereturn isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
  ?
true : false ; // return true?>

Andrew Penry

17 years ago

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.

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:

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.

Hayley Watson

5 years ago

If you regard isset() as indicating whether the given variable has a value or not, and recall that NULL is intended to indicate that a value is _absent_ (as said, somewhat awkwardly, on its manual page), then its behaviour is not at all inconsistent or confusing.

It's not just to check for uninitialised variables - a lot of the time those are just due to sloppy coding. There are other ways a variable could fail to have a value (e.g., it's meant to hold the value returned from a function call but the function didn't have a value to return) where uninitialising the variable would not be an option nor even make sense (e.g., depending on what was to be done with the returned value).

Anl zselgin

13 years ago

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.

packard_bell_nec at hotmail dot com

14 years ago

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.

Ashus

13 years ago

Note that array keys are case sensitive.

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

will report:
bool(true) bool(false)

randallgirard at hotmail dot com

16 years ago

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

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

Tee Cee

16 years ago

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".

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:
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.

Is Isset submit PHP?

Use isset() method in PHP to test the form is submitted successfully or not. In the code, use isset() function to check $_POST['submit'] method. Remember in place of submit define the name of submit button. After clicking on submit button this action will work as POST method.

What can I use instead of isset in PHP?

The equivalent of isset($var) for a function return value is func() === null . isset basically does a !== null comparison, without throwing an error if the tested variable does not exist.

What's the difference between isset () and Array_key_exists ()?

Difference between isset() and array_key_exists() Function: The main difference between isset() and array_key_exists() function is that the array_key_exists() function will definitely tells if a key exists in an array, whereas isset() will only return true if the key/variable exists and is not null.

Does PHP empty check Isset?

The isset() and ! empty() functions are similar and both will return the same results. But the only difference is ! empty() function will not generate any warning or e-notice when the variable does not exists.