php教程

isset

(PHP 4, PHP 5, PHP 7)

isset检测变量是否已设置并且非 NULL

说明

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

检测变量是否设置,并且不是 NULL

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

如果一次传入多个参数,那么 isset() 只有在全部参数都以被设置时返回 TRUE 计算过程从左至右,中途遇到没有设置的变量时就会立即停止。

参数

var

要检查的变量。

...

其他变量。

返回值

如果 var 存在并且值不是 NULL 则返回 TRUE,否则返回 FALSE

更新日志

版本 说明
5.4.0

检查字符的非数字偏移量将会返回 FALSE

范例

Example #1 isset() 例子

<?php

$var 
'';

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

// 在后边的例子中,我们将使用 var_dump 输出 isset() 的返回值。
// 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

?>

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

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

// 键 'hello' 的值等于 NULL,所以被认为是未置值的。
// 如果想检测 NULL 键值,可以试试下边的方法。 
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()

PHP 5.4 改变了传入字符串位移时 isset() 的行为。

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

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

Note:

如果使用 isset() 来检查对象无法访问的属性,如果 __isset() 方法已经定义则会调用这个重载方法。

参见

User Contributed Notes

razvan_bc at yahoo dot com 13-Feb-2019 07:25
In these days you can use ISSET to compare a sting length
COOOL! I love php !!!!

<?php
//FIRST:try to run the script like this,
//THEN: try to uncomment the seccond $str=

$yes="SURE!!!";
$no="NOPE !";

$str="12345";//the string is long 5 bytes ?
//$str="123456";

echo !isset($str{5}) ? $yes : $no;

?>
borshak at gmail dot com 24-Jun-2018 03:13
Would be nice to have is_set() alias for more language consistency (alike of is_int, is_bull so on).
venimus at gmail dot com 27-Apr-2018 11:46
Be warned that before checking an array key existence with isset() the key will be typecasted to integer if it is not a string or integer!

See Example #2 in http://php.net/manual/en/language.types.array.php

I.e.

$a = ['test']; // 'test' will have key 0
$key = false;

var_dump(isset($a[$key]) ); // true, because false will be typecasted to 0

It is not a problem with isset but rather the lose typing when you access keys in arrays
Hayley Watson 30-Jul-2017 01:12
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).
dominic dot mayers at meditationstudies dot org 01-Jul-2017 11:24
The comment http://php.net/manual/en/function.is-null.php#80409 brings the interesting point that is_null will throw an error if the variable was not set at all.  So, we can distinguish a variable that is unset through a NULL assignment and a variable that is simply not set at all. However,  the returned value under is_null is the same in both cases, only the error message differs. 

We can define another function that determines if the variable is "set," including "set" by a NULL assignment.  It's a different concept, different definitions  of isset, etc.  Mixing these different concepts can be confusing.

In the current definitions for isset, is_null, NULL, etc., the extra "and is not NULL" in the definition of isset is redundant, because is_null is the opposite of isset.  We should not mix that with the other concept mentioned above.
dominic dot mayers at meditationstudies dot org 01-Jul-2017 09:51
The doc says that isset "determines if a variable is set and is not NULL."  I prefer to simply say that it "determines that a variable is set," that's it. Adding "is not NULL" is redundant, because isset($v) is the same as ! is_null($v) : http://php.net/manual/en/types.comparisons.php.

The  extra "is  not NULL" is actually a bit confusing. Some might start to complain that it would have been simpler to only determine that the variable is set, not realizing that it's exactly what isset does.

The purpose of the redundant "is not NULL" is to bring out that if a  variable is set to NULL,  isset will return false, but it was implicit in the definition of NULL.
kurdtpage at gmail dot com 21-Dec-2016 01:03
The new (as of PHP7) 'null coalesce operator' allows shorthand isset. You can use it like so:

<?php
// 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
p_ignorethis_lbowers at gmail dot com 06-Oct-2016 07:26
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.
ayyappan dot ashok at gmail dot com 24-Mar-2016 07:23
Return Values :
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

<?php
$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.
ohcc at 163 dot com 21-Nov-2015 08:59
When a variable is set and its values is null, isset() returns false.

You can use array_key_exists() to check whether a null value variable exists.

<?php
    $wxc
= null;
   
var_dump( isset( $wxc ) );
   
var_dump( array_key_exists( 'wxc', $GLOBALS ) );
?>

Output of the above example:

bool(false) bool(true)
andreasonny83 at gmail dot com 12-May-2015 11:26
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 );
?>
flobee 08-Nov-2013 02:38
KISS: array_key_exists() is often the answer, not isset()
<?php
$array
['secure'] = null;
if ( isset(
$array['secure'] ) ) {
   
// what happens here?
}?>
marcio at suhdo dot com 07-Jul-2013 11:08
//thin way to set a variable
$foo  = isset($_POST['foo']) ? $_POST['foo'] : null;
uramihsayibok, gmail, com 25-Apr-2013 11:32
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;
       
// }
   
}

    public function
__isset($name) {
        echo
"(isset {$name}?) ";
       
// return whether the property exists
       
return false;
    }

}

$obj = new FatalOnGet();

// works
echo "Testing if ->nosuch exists: ";
if (isset(
$obj->nosuch)) echo "Yes"; else echo "No";

// fatals
echo "\nTesting if ->nosuch->foo exists: ";
if (isset(
$obj->nosuch->foo)) echo "Yes"; else echo "No";

// not executed
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.
Daniel Klein 29-May-2012 03:49
How to test for a variable actually existing, including being set to null. This will prevent errors when passing to functions.

<?php
// false
var_export(
 
array_key_exists('myvar', get_defined_vars())
);

$myvar;
// false
var_export(
 
array_key_exists('myvar', get_defined_vars())
);

$myvar = null;
// true
var_export(
 
array_key_exists('myvar', get_defined_vars())
);

unset(
$myvar);
// false
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.
qeremy 07-Mar-2012 03:36
Simple solution for: "Fatal error: Can't use function return value in write context in ..."

<?php
function _isset($val) { return isset($val); }
?>
benallfree at gmail dot com 21-Apr-2011 06: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 05: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 22-Dec-2010 07: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

?>
i [at] nemoden [dot] com 14-Jun-2010 11: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
?>
Anl zselgin 14-Aug-2009 03: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.
Ashus 08-Dec-2008 01: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)
a dot schaffhirt at sedna-soft dot de 12-Oct-2008 08: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
?>
mark dot fabrizio at gmail dot com 15-Sep-2008 07: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 02: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.
anonymousleaf at gmail dot com 25-Feb-2008 10: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 04: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 11: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.
talbutt(at)mail(dot)med(dot)upenn(edu) 13-Aug-2007 08: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 04: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 01: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 12: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.
randallgirard at hotmail dot com 27-Sep-2006 11: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
Tee Cee 20-Aug-2006 05: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.
21-Jul-2006 07: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 06: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.
Slawek Petrykowski 29-Nov-2005 03: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 !
14-Sep-2005 03: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.
Andrew Penry 11-May-2005 08: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.
yaogzhan at gmail dot com 20-Mar-2005 04: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'.
pianistsk8er at gmail dot com 09-Dec-2004 06: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 02: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

CopyRight © 2008-2022 verySource.Com All Rights reserved. 京ICP备17048824号-1 京公网安备:11010502034788