在PHP中,如果值存在,则返回数组的键。

4

如何最快地检查一个变量是否以其值的形式存在于数组中,并返回其键?

例如:

$myArray = [ "test" => 1, "test2" = 2, "test3" = 3];

$var = [1,6,7,8,9];

我需要的是 如果($var 在 $myArray 中) return (在这种情况下) “test”。这是否可能不使用两个循环?是否有类似于in_array()的函数,如果找到返回值的键?

4
使用array_search()函数。 - undefined
@Dinidu 编辑时,请同时删除诸如“嗨”、“谢谢”等内容。 - undefined
array_search是我正在寻找的,谢谢。@jothi - undefined
1
var_dump( array_keys(array_intersect($myArray, $var)) ); - undefined
@hjpotter92 我也考虑过这个问题,不过我的观点是要保持帖子的原汁原味。我会在未来的编辑中删除它们。谢谢你的评论。 - undefined
6个回答

7
你可以使用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,因此最好使用如我上面示例中所示的 === 运算符。

查看文档以获取更多信息。


3
你可以使用 array_search 函数。 http://php.net/manual/zh/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";
    }
}

3
<?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!              
}

1
不需要使用两个循环。
使用'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) }

1
尽管这段代码可能有助于解决问题,但提供关于为什么和/或如何回答问题的额外上下文将显著提高其长期价值。请编辑您的答案以添加一些解释。 - undefined

1
使用array_search()函数。
foreach ($var as $row) 
{
   $index_val = array_search($row, $myArray);

  if ($index_val === false) 
  {

     echo "not present";
  } 
 else
 {
     echo "presented";
  }
}

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";
        }
    }
    ?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接