October 2005
Intermediate to advanced
372 pages
11h 35m
English
array_intersect()
array array_intersect ( arrayarr1, arrayarr2[, array ...] )
The array_intersect() function returns a new array containing all the values of array $arr1 that exist in array $arr2.
$toppings1 = array("Pepperoni", "Cheese", "Anchovies", "Tomatoes");
$toppings2 = array("Ham", "Cheese", "Peppers");
$int_toppings = array_intersect($toppings1, $toppings2);
var_dump($int_toppings);
// prints: array(1) { [1]=> string(6) "Cheese" }The array_intersect() function will try to retain array keys when possible. For example, if you are intersecting two arrays that have no duplicate keys, all the keys will be retained. However, if there are key clashes, array_intersect() will use the first array to contain it. For example:
$arr1 = array("Paul"=>25, "Ildiko"=>38, "Nick"=>27);
$arr2 = array("Ildiko"=>27, "Paul"=>38);
print "\nIntersect:\n";
var_dump(array_intersect($arr1, $arr2));
// Values 27 and 38 clashes, so their keys from $arr1 are used.
// So, output is Ildiko (38), and Nick (27)You can intersect several arrays simultaneously by providing more parameters to the function. For example:
$arr1_shared = array_intersect($arr1, $arr2, $arr3, $arr4);