在数组中查找共享的vales,放入anothyer数组中

时间:2015-08-20 20:23:17

标签: php arrays

我一直试图找到这个没有运气的答案,所以如果有人可以提供帮助,我会非常感激。在PHP中是否有一个函数可以比较2个数组并在第3个数组中放置匹配值?另外我想知道如何确定是否有任何匹配,比如布尔值。

 $array1 = array (1,2,3,4);
    $array2 = array (1, 2, 7,8);

    //I want to have an array like $array3 after comparing $array1
    //and $array2.....also I want to know if values were placed in 
    //$array3 or not.

    $array3 = array(1,2);

2 个答案:

答案 0 :(得分:0)

您可以使用array_intersect

从手册:

$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);

产生:

Array
(
    [a] => green
    [0] => red
)

如果你想检查是否有匹配你可以做:

empty($result) //true if empty, meaning no matches

手动输入为here。我借了第一个例子。

答案 1 :(得分:0)

$array1 = array (44,2,3,4);
$array2 = array (44,2,7,8);
//I want to have an array like array 3 after comparing $array1
//and $array2.....also I want to know if values were placed in 
//$array3 or not.
$array3 = array(44,2);


$result = array_intersect($array1, $array2);

   if ($result){
   $match = true;
   echo $result [0];

   }
   else{
   $match = false;
   }

if ($match === true){
    // Do something
}
else{
    //do something else
    }