Name

array_intersect()

Synopsis

    array array_intersect ( array arr1, array arr2 [, 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);

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.