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
?>
isset
(PHP 4, PHP 5)
isset — 変数がセットされているかどうかを検査する
説明
bool isset ( mixed $var [, mixed $var [, $...]] )var が存在すればTRUE、 そうでなければFALSEを返します。
変数が、unset() により割当を解除された場合、 isset() はもうTRUEとはなりません。 NULLに設定されている変数を調べた場合、 isset() はFALSEを返します。 NULLバイト("\0")はPHPの定数 NULLと等価ではないことにも注意してください。
Warning: isset() は何らかの値が渡された 変数の場合のみ動作します。そうでない場合、パースエラーとなります。 もし 定数 が設定されているかどうかをチェックする場合は、 defined() を使用してください。
<?php
$var = '';
// これは TRUE と評価されるので、テキストが出力される
if (isset($var)) {
echo "This var is set so I will print.";
}
// 次の例では、isset() の戻り値を出力するため var_dump を
// 使用している
$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_dump(array_key_exists('hello', $a)); // TRUE
?>
注意: これは、関数ではなく 言語構造のため、可変関数 を用いて コールすることはできません。
empty(), unset(), defined(), PHP 型の比較表, array_key_exists(), is_null(), エラー制御演算子 @ も参照ください。
isset
beuc at beuc dot net
01-Jan-2007 06:56
01-Jan-2007 06:56
beuc at beuc dot net
17-Dec-2006 05:35
17-Dec-2006 05: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 03:04
04-Dec-2006 03: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
30-Nov-2006 08:14
30-Nov-2006 08: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
28-Sep-2006 03:51
28-Sep-2006 03: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...
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
30-Aug-2006 02:09
30-Aug-2006 02: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 09:20
20-Aug-2006 09: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 04:13
17-Aug-2006 04:13
fyi:
you *cannot* do assignments inside of the isset() function. although you *can* while inside of other functions such as is_null().
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 09:26
16-Aug-2006 09: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 11: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 10:12
14-Apr-2006 10: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
10-Mar-2006 03:27
10-Mar-2006 03: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 03:02
10-Feb-2006 03: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 08:06
29-Nov-2005 08: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 04:16
21-Sep-2005 04: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 07: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.
php [at] barryhunter [.] co [.] uk
08-Sep-2005 04:47
08-Sep-2005 04:47
In case it helps someone, here's a table to compare different Variable tests/comparisons
http://www.deformedweb.co.uk/php_variable_tests.php
onno at itmaze dot com dot au ##php==owh
12-Aug-2005 04:33
12-Aug-2005 04: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 03:38
11-Jun-2005 03: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 05:03
25-May-2005 05: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
12-May-2005 12:17
12-May-2005 12: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
11-Apr-2005 12:33
11-Apr-2005 12: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 09:52
20-Mar-2005 09: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
02-Mar-2005 08:13
02-Mar-2005 08: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 03:21
07-Feb-2005 03: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 11:23
10-Dec-2004 11: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 07:35
15-Nov-2004 07: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
08-Dec-2003 03:19
08-Dec-2003 03: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
09-Sep-2003 06:16
09-Sep-2003 06: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 "false" or "null"<br>";
}
if(!$var) {
// if false or "null": go on here
echo "2. var has no value $var<br>";
} else {
echo "2. var is "false" or "null"<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>";
}
?>
05-May-2000 09:11
To find out what member vars are defined in a class, use the get_class_vars() function (see http://www.php.net/manual/function.get-class-vars.php)