-1

I have been trying to find the answer to this one with no luck, so if anyone can help I would really appreciate it. is there a function in PHP which can compare 2 arrays and place matching values in a 3rd array? Also I wonder how I could determine if there were any matches or not, like a boolean.

 $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);
Rodger123
  • 33
  • 6
  • there is a function in the manual for this - im sure a search will find **i**t –  Aug 20 '15 at 20:25
  • What you are trying to do is to find the "intersection" of two sets using the `array_intersect()` function. You might want update your question to be clearer. There is a great example left in the [array_intersect() comments](http://php.net/manual/en/function.array-intersect.php#84286) that clearly illustrates what you are trying to achieve. – Saïd Aug 20 '15 at 21:56

2 Answers2

0

You could use array_intersect

From the manual:

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

Which produces:

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

If you want to check if there were matches you can do:

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

Manual entry is here. I borrowed the first example.

JSelser
  • 3,510
  • 1
  • 19
  • 40
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
    }
Rodger123
  • 33
  • 6