Check the common elements of two arrays

Discuss coding issues, and scripts related to PHP and MySQL.
Marius
Posts:107

Check the common elements of two arrays

Hi
I have two arrays $a1 and $a2 with various elements.
How can I check which item from $a2 is in $a1? Is there any function, or I have to traverse with a for() instruction the $a2 items and compare with elements of $a1?

Admin Posts:805
Hi,
The array_intersect($a2, $a1) function returns the elements of $a2 which are found in $a1.
Also, with the in_array() function you can check if a value exists into an array.
Example:

Code: Select all

$a1 = array('a', 'e', 'i', 'o', 'u');
$a2 = array('b', 'e', 'd', 5, 'u', 'x', 'z');

// get common elements (key=>item of $a2 which is in $a1 too)
$a1_2 = array_intersect($a1, $a2);
var_export($a1_2);    // array (1 => 'e', 4 => 'u')

// check if an item of $a2 is in $a1
if(in_array($a2[4], $a1)) echo 'ok';
else echo 'no';