PHP - 检查数组索引是否存在或为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15310261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - Checking if array index exist or is null
提问by Virus721
Is there a way to check if an array index exists or is null?
isset()doesn't tell you whether the index doesn't exist or exists but is null.
If I do : isset($array[$index]) || is_null($array[$index])it won't work because if the index doesn't exist is_null will crash.
有没有办法检查数组索引是否存在或为空?
isset()不会告诉您索引是不存在还是存在但为空。如果我这样做:isset($array[$index]) || is_null($array[$index])它将不起作用,因为如果索引不存在 is_null 将崩溃。
How can I check this please? Also is there a way to check only if something exist, no matter if it is set to null or not?
请问这个怎么查?有没有办法只检查某些东西是否存在,无论它是否设置为空?
回答by Virus721
The function array_key_exists()can do that, and property_exists()for objects, plus what Vineet1982 said. Thanks for your help.
函数array_key_exists()可以做到这一点,property_exists()用于对象,加上 Vineet1982 所说的。谢谢你的帮助。
回答by Vineet1982
This is the very good question and you can use get_defined_vars() for this:
这是一个很好的问题,您可以为此使用 get_defined_vars():
$foo = NULL;
$a = get_defined_vars();
if (array_key_exists('def', $a)) {
// Should evaluate to FALSE
};
if (array_key_exists('foo', $a)) {
// Should evaluate to TRUE
};
This will solve your problem
这将解决您的问题
回答by Teerath Kumar
Simplest defined in: http://php.net/manual/en/function.array-key-exists.php
最简单的定义在:http: //php.net/manual/en/function.array-key-exists.php
<?php
$array=array('raja'=>'value', 'john'=>'value2');
$var='raja';
echo array_key_exists($var, $array);
?>

