PHP has an array_intersect() function that can do this. As an example, ypo can put the following code into PHPFiddle for testing:
<?php
$array1 = array('ace', 'one', 'five', 'nine', 'elephant');
$array2 = array('elephant', 'seven', 'ace', 'jack', 'queen');
print_r($array1); print('<br>');
print_r($array2); print('<br>');
print_r(array_intersect($array1, $array2)); print('<br>');
?>
Then you'll see that it gives you what you want (reformatted for readability):
Array ( [0] => ace
[1] => one
[2] => five
[3] => nine
[4] => elephant )
Array ( [0] => elephant
[1] => seven
[2] => ace
[3] => jack
[4] => queen )
Array ( [0] => ace
[4] => elephant )
Do note that this does not actually give you consecutive keys in the result, the keys appear to come from the first array given to array_intersect()
. If it's important that you get a consecutively-indexed array, you may need a post-processing step to adjust it. Something like this should be a good start (modification to original fiddle to use consecutive indexes):
<?php
$array1 = array('ace', 'one', 'five', 'nine', 'elephant');
$array2 = array('elephant', 'seven', 'ace', 'jack', 'queen');
print_r($array1); print('<br>');
print_r($array2); print('<br>');
$array3 = array();
foreach (array_intersect($array1, $array2) as $val) {
array_push($array3, $val);
}
print_r($array3); print('<br>');
?>