Other code examples of isset being used
"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.
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'.
To organize some of the frequently used functions..
<?php
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;
}
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){
}
?>
How to test for a variable actually existing, including being set to null. This will prevent errors when passing to functions.
<?php
var_export(
array_key_exists('myvar', get_defined_vars())
);
$myvar;
var_export(
array_key_exists('myvar', get_defined_vars())
);
$myvar = null;
var_export(
array_key_exists('myvar', get_defined_vars())
);
unset($myvar);
var_export(
array_key_exists('myvar', get_defined_vars())
);
if (array_key_exists('myvar', get_defined_vars())) {
myfunction($myvar);
}
?>
Note: you can't turn this into a function (e.g. is_defined($myvar)) because get_defined_vars() only gets the variables in the current scope and entering a function changes the scope.
<?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 !
Here is an example with multiple parameters supplied
<?php
$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:
<?php
$var = array();
$var['val1'] = 'test';
$var['val2'] = 'on';
if ( isset( $var['val1'] ) && isset( $var['val2'] ) && $var['val2'] === 'on' ) {
unset( $var['val1'] );
}
print_r( $var );
?>
isset expects the variable sign first, so you can't add parentheses or anything.
<?php
$foo = 1;
if(isset(($foo))) { $foo = 2;
}
?>
Simple solution for: "Fatal error: Can't use function return value in write context in ..."
<?php
function _isset($val) { return isset($val); }
?>
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('foo'=>null);
return isset($array['foo']) || array_key_exists('foo',$array)
? true : false ; return isset($array['inexistent']) || array_key_exists('inexistent',$array)
? true : false ; class bar
{
static $foo=null;
}
return isset(bar::$foo) || array_key_exists('foo',get_class_vars('bar'))
? true : false ; return isset(bar::$inexistent) || array_key_exists('inexistent',get_class_vars('bar'))
? true : false ; class bar
{
public $foo=null;
}
$bar=new bar();
return isset($bar->foo) || array_key_exists('foo',get_object_vars($bar))
? true : false ; return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
? true : false ; $bar=new stdClass;
$bar->foo=null;
return isset($bar->foo) || array_key_exists('foo',get_object_vars($bar))
? true : false ; return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
? true : false ; ?>
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 {
public function __get($name) {
echo "(getting {$name}) ";
echo "Property does not exist!";
exit;
}
public function __isset($name) {
echo "(isset {$name}?) ";
return false;
}
}
$obj = new FatalOnGet();
echo "Testing if ->nosuch exists: ";
if (isset($obj->nosuch)) echo "Yes"; else echo "No";
echo "\nTesting if ->nosuch->foo exists: ";
if (isset($obj->nosuch->foo)) echo "Yes"; else echo "No";
echo "\nTesting if ->irrelevant exists: ";
if (isset($obj->irrelevant)) echo "Yes"; else echo "No";
?>
Testing if ->nosuch exists: No
Testing if ->nosuch->foo exists: Property does not exist!
Uncomment the echos in the methods and you'll see exactly what happened:
Testing if ->nosuch exists: (isset nosuch?) No
Testing if ->nosuch->foo exists: (getting nosuch) Property does not exist!
On a similar note, if __get always returns but instead issues warnings or notices then those will surface.
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.
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.
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.
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)); var_dump(isset($abc->def)); var_dump(isset($abc->def->ghi)); var_dump(isset($abc->def->ghi->jkl)); var_dump(isset($def)); var_dump(isset($def->ghi)); var_dump(isset($def->ghi->jkl)); var_dump($abc); var_dump($abc->def); var_dump($abc->def->ghi); var_dump($abc->def->ghi->jkl); var_dump($def); var_dump($def->ghi); var_dump($def->ghi->jkl); ?>
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'); if (true === isset($null)){echo 'isset($null) === true'} else {echo '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';} if (true === array_key_exists('null', get_defined_vars())) {echo '$null exists';} else {echo '$null does not exist';} ?>
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)
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)); var_dump(isset($x->bar_exists)); ?>
[EDITOR thiago NOTE: This snippet has improvements by "Paul Lashbrook"]
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;
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); var_dump($a=&$c); var_dump(isset($c)); var_dump($a = 5); var_dump($c); unset($c);
var_dump($a=&$c); var_dump(isset($c)); unset($c);
var_dump($a = 5); var_dump($c); ?>
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())); var_dump(isset($c)); var_dump($c); var_dump((string)$c);
var_dump(print_r($c,true));
var_dump($a=$c);
var_dump(array_key_exists('c',get_defined_vars())); var_dump($c = NULL); var_dump(array_key_exists('c',get_defined_vars())); var_dump(isset($c)); unset($c); var_dump(array_key_exists('c',get_defined_vars())); var_dump($a=&$c);
var_dump(array_key_exists('c',get_defined_vars())); unset($c); var_dump(&$c); var_dump(array_key_exists('c',get_defined_vars())); ?>
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.
In PHP4, the following works as expected:
<?php
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:
<?php
if (is_array($obj->thing) && isset($obj->thing['key'])) {
unset($obj->thing['key']) ;
}
?>
I found something interesting while working with isset() in PHP5.5+
<?php
$a = "foo";
$b = "bar";
var_dump(isset($a, $b)); unset($b);
var_dump(isset($a,$b)); ...BUT...
var_dump(!isset($a,$b));
<?php
return isset($nonexistentarray['foo']);
?>
Returns false without trouble (assuming $nonexistent array does not exist).
<?php
$foo = 17;
return isset($nonexistentarray[$foo]);
?>
Also returns false without trouble.
But, oddly,
<?php
return isset($nonexistentarray[$nonexistentkey]);
?>
While returning false, also triggers a notice regarding the undefined variable "$nonexistentkey".
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.
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;
}
$first_name = isset_or($_POST['first_name'], "Empty");
$total = isset_or($row['total'], 0);
?>
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>';
?>
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
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.
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;
}
$id = intval(ifsetor($_GET['id'], 0));
?>
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) ;
}
?>
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)); ?>
<?php
$b = '2';
echo issetOr($a,issetOr($b,3)); ?>
<?php
echo issetOr($a,issetOr($b,3)); ?>
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.
just as note: if you want to check variables by boolean value: true or false , "isset" has a different meaning!
<?php
$var=null;
if($var) {
echo "1. var is true or has a value $var<br>";
} else {
echo "1. var is "false" or "null"<br>";
}
if(!$var) {
echo "2. var has no value $var<br>";
} else {
echo "2. var is "false" or "null"<br>";
}
$var =false;
if(isset($var)) {
echo "3. var has value: $var<br>";
}
$var=null;
if(!isset($var)) {
echo "4. var was not set $var<br>";
}
?>
KISS: array_key_exists() is often the answer, not isset()
<?php
$array['secure'] = null;
if ( isset( $array['secure'] ) ) {
}?>
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.
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.
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'; if (is_null($var = $_GET['key'])) echo 'whatever'; ?>
hope someone finds this useful.