PHP compare two arrays and get the matched values not the difference

Julian Paolo Dayag picture Julian Paolo Dayag · Apr 2, 2012 · Viewed 104k times · Source

I'm trying to compare two arrays and get only the values that exist on both arrays but, unfortunately, I can't find the right array function to use...

I found the array_diff() function: http://php.net/manual/en/function.array-diff.php

But it's for the difference of the both arrays.

Example:

$array1 = array("**alpha**","omega","**bravo**","**charlie**","**delta**","**foxfrot**");
$array2 = array("**alpha**","gamma","**bravo**","x-ray","**charlie**","**delta**","halo","eagle","**foxfrot**");

Expected Output:

$result = array("**alpha**","**bravo**","**charlie**","**delta**","**foxfrot**");

Answer

Alix Axel picture Alix Axel · Apr 2, 2012

Simple, use array_intersect() instead:

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