我要在哪个数组中寻找值?

时间:2019-12-02 09:48:42

标签: php arrays

我在PHP中有两个或两个以上的数组。例如:

$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];

我想找到这些数组中哪个包含值5,这样我就可以创建输出“ $ array1 contains 5”

5 个答案:

答案 0 :(得分:1)

尝试一下,

$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];
$f = 5;

for($n=1;$n<=3;$n++){
    if(in_array($f, ${"array" . $n})){
        echo "\$array$n contains $f";
    }
}

编辑其他变量名称

$zomer = [1,5,10,15,22,28];
$halil = [1,8,12,16,25,30];
$kaya= [10,15,20,21,22]; 
$f = 5;
$collection = compact("zomer","halil","kaya");

foreach ($collection as $key=>$val){
    if(in_array($f, $collection[$key])){
        echo "\$$key contains $f";
    }
}

答案 1 :(得分:0)

如@KrijnToet所说,可以借助in_array()函数轻松完成:

if(in_array($val, $array1)) echo $val.' comes from $array1'.PHP_EOL;

Demo

答案 2 :(得分:0)

遵循这些思路可能会有所帮助:

向函数findVal()输入要查找的数组和一个needle值,它将返回保存它的数组的名称。

<?php
$array1 = [1, 5, 10, 15, 22, 28];
$array2 = [1, 8, 12, 16, 25, 30];
$array3 = [10, 15, 20, 21, 22];

findVal([$array1, $array2, $array3], 30);

function findVal($arrays = [], $needle)
{
    foreach ($arrays as $key => $array) {
        foreach ($array as $value) {
            if ($value == $needle) {
                foreach ($GLOBALS as $arrayName => $value) {
                    if ($value === $array) {
                        echo 'value ' . $needle . ' found in : ' . $arrayName;
                    }
                }
            }
        }
    }
}

$GLOBALS —引用全局范围内所有可用的变量,因此我们可以使用它来检索数组名称。

demo

答案 3 :(得分:0)

<?php

$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];

$compacted = compact('array1', 'array2', 'array3');

$needle = 21;
$found = array_filter($compacted, function($item) use ($needle) {
    return in_array($needle, $item);
});

var_export(array_keys($found));

输出:

array (
    0 => 'array3',
  )

答案 4 :(得分:0)

尝试一下,使用此功能,我们可以搜索任意数量的数组

$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];
$findval=5;
$arrayFinal = array('array1' =>$array1 ,'array2' =>$array2 ,'array3' =>$array3 );
function searchForId($find, $array) {
   foreach ($array as $key=> $value) {
      if(in_array($find, $value)){
         echo "\$$key contains $find";
      }
   }
}
searchForId($findval,$arrayFinal); //Call function