<?PHP $arr1=array(1,2,3,4,5,6,7,8,9); $arr2=array(2,4,6,8); $arr3=array_intersect($arr1,$arr2); foreach($arr3 as $element) echo "$element, "; //2, 4, 6, 8, ?>
If more than 2 arrays are compared, only elements contained in all arrays will be returned.
<?PHP $arr1=array(1,2,3,4,5,6,7,8,9); $arr2=array(2,4,6,8); $arr3=array_intersect($arr1,$arr2,array(2,4)); foreach($arr3 as $element) echo "$element, "; //2, 4 ?>
It can also take associative arrays, both the keys and values will be compared.
<?PHP $arr1=array("apple"=>2.2,"rice"=>0.5,"nuts"=>4.99,"meat"=>6.99); $arr2=array("apple"=>1.2,"rice"=>0.5,"orange"=>1.99); $arr = array_intersect($arr1,$arr2); print_r($arr); //the result is: Array ( [rice] => 0.5 ) ?>
array_diff() function compares arrays and returns all the elements in the 1st array but not in the 2nd array.
<?PHP $arr1=array(1,2,3,4,5,6,7,8,9); $arr2=array(2,4,6,8); $arr3=array(1,3); $arr=array_diff($arr1,$arr2,arr3); foreach($arr as $element) echo "$element, "; //5, 7, 9, ?>
<?PHP $arr1=array("apple"=>2.2,"rice"=>0.5,"nuts"=>4.99,"meat"=>6.99); $arr2=array("apple"=>1.2,"rice"=>0.5,"orange"=>1.99); $arr = array_intersect_key($arr1,$arr2); print_r($arr); //the result is: Array ( [apple] => 2.2 [rice] => 0.5 ) ?>