isset

Description

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 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 set. Evaluation goes from
left to right and stops as soon as an unset variable is encountered.

Parameters

var

The variable to be checked.

...

Another variable ...

Return Values

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

Changelog

Version

Description

5.4.0

Checking non-numeric offsets of strings now returns FALSE.

Examples

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

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

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.

Note that isset() is not recursive as of the 5.4.8 I have available here to test with: if you use it on a multidimensional array or an object it will not check isset() on each dimension as it goes.

Imagine you have a class with a normal __isset and a __get that fatals for non-existant properties. isset($object->nosuch) will behave normally but isset($object->nosuch->foo) will crash. Rather harsh IMO but still possible.

<?php

class FatalOnGet {

// pretend that the methods have implementations that actually try to do work // in this example I only care about the worst case conditions

public function __get($name) { echo "(getting {$name}) ";

// if property does not exist {echo "Property does not exist!"; exit;// }}

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.

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.

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:

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.

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

Some thought shows that this is the right behaviour (we're testing for the existence of an array element, but we need to know which array element we're testing the existence of), but it probably isn't obvious. This implies that:<?php$extantarray[null] = 42;return isset($extantarray[$nonexistentkey]);?>Triggers a notice and returns true.

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

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.

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.

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.

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'])

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

<?phpif (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:<?phpif (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';?>

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.

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.

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

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.

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

This is very simple implementation of issetor() for PHP. It works like ?? in C#, // in Perl (it can access undefined hash keys without it nevertheless) or ? in CoffeeScript (also can access undefined hash keys too). You shouldn't use directly $_GET['something'] (it can generate E_NOTICEs in case somebody would try hacking your site), but isset($_GET['something']) ? $_GET['something'] : '' is long for many people (for so common operation). This alternative makes using superglobals easier.

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.

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