簡體   English   中英

如果值存在,則返回數組的鍵PHP

[英]return key of array if value is present PHP

檢查數組中是否存在變量並將其返回鍵的最快方法是什么?

例:

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

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

我需要的是if($var is in $myArray) return (in this case) “測試”。

如果不做兩個循環就可以嗎? 是否有類似in_array()函數返回找到的值的鍵?

您可以使用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,因此最好使用===運算符,如下所示在上面的例子中

查看文檔以了解更多

您可以使用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";
    }
}
<?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!              
}

使用array_search()

foreach ($var as $row) 
{
   $index_val = array_search($row, $myArray);

  if ($index_val === false) 
  {

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM