PHP数组_搜索始终返回数组的第一个键
我最近注意到在代码中使用array_search函数时出现了问题。我正在数组“$allcraftatts”中搜索值“sharp”。我试图通过设置一个双线实验来隔离问题:PHP数组_搜索始终返回数组的第一个键,php,arrays,function,Php,Arrays,Function,我最近注意到在代码中使用array_search函数时出现了问题。我正在数组“$allcraftatts”中搜索值“sharp”。我试图通过设置一个双线实验来隔离问题: $testcopy=$allcraftatts; $testsharp=array_search("sharp", $testcopy); 稍后使用“print_r(get_defined_vars());”可以得到以下结果: [testcopy] => Array (
$testcopy=$allcraftatts;
$testsharp=array_search("sharp", $testcopy);
稍后使用“print_r(get_defined_vars());”可以得到以下结果:
[testcopy] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => Sharp Stone
[7] => Sharp Stones
[8] => stone
[9] => object
[10] => sharp
[11] => hard
[12] => 0
[13] => 0
[14] => 0
[15] => 0
[16] => 0
[17] => 0
[18] => 0
)
[testsharp] => 0
我确保在其他任何时候都不会修改这些变量
现在,如果我将代码更改为
$testcopy=$allcraftatts;
unset($testcopy[0]);
$testsharp=array_search("sharp", $testcopy);
它返回“1”
这让我相信它总是返回数组中的第一个键
这让我困惑!这是一个让你担心语言本身有问题的bug。不管这有多可疑,我最终还是被驱使去查看PHP源代码中的错误,但不幸的是,我无法理解它
看到这是一个如此简单的函数,我肯定会被这个不可避免的简单答案彻底羞辱,但在这一点上,我只想要一个答案。
array\u search
正在使用=
在搜索过程中比较值
表单PHP文档
如果第三个参数strict设置为TRUE,那么array_search()函数将在haystack中搜索相同的元素。这意味着它还将检查大海捞针的类型,并且对象必须是相同的实例
因为第一个元素是0
,所以在搜索过程中字符串被转换为0
简单测试
var_dump("sharp" == 0); //true
var_dump("sharp" === 0); //false
解决方案使用strict
选项搜索相同的值
$testsharp = array_search("sharp", $testcopy,true);
^---- Strict Option
var_dump($testsharp);
输出
10
如果搜索键之前的任何键为数字零,则返回该键,因为该键正在执行由数组的数据类型主导的“松散”匹配,“夏普”(如果转换为
int
)计为零。通过严格检查,可以找到正确的值
否则,通过执行
$testcopy = array_map('strval', $testcopy);
为了将值转换为字符串,它还可以与“松散”检查一起使用。欢迎来到松散键入的奇妙世界。在php中,数组搜索默认为非严格比较(“==”),但可以添加第三个参数以强制严格(“==”)。您几乎总是希望严格,尽管有时非严格是正确的操作 请查看以下内容:
$allcraftatts = array(0, 0, 0, 0, 0, 0, "Sharp Stone", "Sharp Stones", "stone", new stdClass(), "sharp", "hard", 0, 0, 0, 0, 0,0 ,0);
$testcopy=$allcraftatts;
$testsharp=array_search("sharp", $testcopy);
$testsharpStrict=array_search("sharp", $testcopy, true);
print_r(get_defined_vars());
if(0 == "sharp"){
echo "true for == \n";
}else{
echo "false == \n";
}
if(0 === "sharp"){
echo "true for === \n";
}else{
echo "false === \n";
}
以及输出:
[testcopy] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => Sharp Stone
[7] => Sharp Stones
[8] => stone
[9] => stdClass Object
(
)
[10] => sharp
[11] => hard
[12] => 0
[13] => 0
[14] => 0
[15] => 0
[16] => 0
[17] => 0
[18] => 0
)
[testsharp] => 0
[testsharpStrict] => 10
)
true for ==
false ===
您使用的是什么版本的PHP?您还可以向我们显示这些变量的
var\u dump
输出,而不是print\r
?它将显示您是否有任何额外的空格(这是人们在array\u search
中常见的打嗝体验)