Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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);
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page