php array_search 0 索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15934392/
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 array_search 0 index
提问by meagar
It seems that that you can not use the search_array function in PHP to search the 0 index AND have it evalute as true.
似乎您不能使用 PHP 中的 search_array 函数来搜索 0 索引并将其评估为真。
Consider this code for example:
例如,考虑以下代码:
$test=array(100, 101, 102, 103);
if($key=array_search(100,$test)){
echo $key;
}
else{
echo "Not found";
}
The needle '100' is found in the haystack and the key is returned as 0. So far so good, but then when I evaluate whether the search was successful or not it fails because the returned value is 0, equal to false!
在 haystack 中找到了针 '100' 并且键返回为 0。到目前为止很好,但是当我评估搜索是否成功时它失败了,因为返回值是 0,等于 false!
The php manual suggests using '!==' but by doing so the key (array index) is not returned, instead either 1 or 0 is returned:
php 手册建议使用 '!==' 但这样做不会返回键(数组索引),而是返回 1 或 0:
if($key=(array_search(103,$test)!== false)){
}
So how can I successfully search the array, find a match in the 0 index and have it evaluate as true?
那么如何成功搜索数组,在 0 索引中找到匹配项并将其评估为真?
回答by meagar
This is explicitly mentioned in the docs. You need to use ===
or !==
:
文档中明确提到了这一点。您需要使用===
或!==
:
$key = array_search(...);
if ($key !== false) ...
Otherwise, when $key
is 0
, which evaluates to false
when tested as a boolean.
否则, when $key
is 0
,其计算结果为false
when 作为布尔值进行测试。
回答by Explosion Pills
The conditional in your second example block gives execution order priority to the !==
operator, you want to do the opposite though.
第二个示例块中的条件为!==
运算符提供了执行顺序优先级,但您想要做相反的事情。
if (($key = array_search(100,$test)) !== false) {
!==
has higherprecedence than ==
which makes the parentheses necessary.
!==
具有更高的优先级,==
这使得括号成为必要。
回答by Andrej Bestuzhev
$key = array_search($what, $array);
if($key !== false and $array[$key] == $what) {
return true;
}
it's more secure
它更安全
回答by rorra
$test=array(100, 101, 102, 103);
if (($key = array_search(100,$test)) === false) {
echo "Not found";
} else{
echo $key;
}
回答by Peter Kiss
if(($key = array_search(103,$test)) !== false){
}