检查变量是否存在于数组中作为其值并返回其键的最快方法是什么?
示例:
$myArray = [ "test" => 1, "test2" = 2, "test3" = 3];
$var = [1,6,7,8,9];
我需要的是if($var is in $myArray) return (in this case)
"测试"。
这可以不做两个循环吗?
是否有in_array()
等函数返回值的键,如果找到了?
答案 0 :(得分:3)
您可以使用array_search
foreach($var as $value)
{
$key = array_search($value, $myArray);
if($key === FALSE)
{
//Not Found
}
else
{
//$key contains the index you want
}
}
注意,如果找不到该值,该函数将返回false
,但它也可能返回一个可以与false相同的值处理的值,例如基于零的数组上的0,因此它'最好使用===
运算符,如上例所示
查看documentation了解更多
答案 1 :(得分:2)
您可以使用array_search
http://php.net/manual/en/function.array-search.php
array_search - 在数组中搜索给定值,如果成功则返回相应的键
示例:强>
$myArray = ["test" => 1, "test2" = 2, "test3" = 3];
$var = [1, 6, 7, 8, 9];
foreach ($var as $i) {
$index = array_search($i, $myArray);
if ($index === false) {
echo "$i is not in the array";
} else {
echo "$i is in the array at index $index";
}
}
答案 2 :(得分:2)
<?php
//The values in this arrays contains the values that should exist in the data array
$var = [1,6,7,8,9];
$myArray = [ "test" => 1, "test2" = 2, "test3" = 3];
if(count(array_intersect_key(array_flip($myArray), $var)) === count($var)) {
//All required values exist!
}
答案 3 :(得分:1)
使用array_search()
foreach ($var as $row)
{
$index_val = array_search($row, $myArray);
if ($index_val === false)
{
echo "not present";
}
else
{
echo "presented";
}
}
答案 4 :(得分:0)
Dnt需要使用2loops
使用'array_intersect'。
'array_intersect'将返回两个数组中的公共值
如果你想要匹配键,那么使用'array_intersect_key'
$myArray = array("test" => 1, "test2" => 2, "test3" => 3);
$var = array(1,6,7,8,9);
$intersect=array_intersect($myArray, $var);
var_dump($intersect);
输出:
array(1) {
["test"]=> int(1) }
答案 5 :(得分:0)
<?php
dont missed => wehere "test2" & "test3"
$myArray = ["test" => 1, "test2" => 2, "test3" => 3];
$var = [1, 6, 7, 8, 9];
foreach ($var as $i) {
$index = array_search($i, $myArray);
if ($index === false) {
echo "$i is not in the array";
} else {
echo "$i is in the array at index $index";
}
}
?>