Name

array_diff()

Synopsis

    array array_diff ( array arr1, array arr2 [, array ...] )

The array_diff() function returns a new array containing all the values of array $arr1 that do not exist in array $arr2.

    $toppings1 = array("Pepperoni", "Cheese", "Anchovies", "Tomatoes");
    $toppings2 = array("Ham", "Cheese", "Peppers");
    $diff_toppings = array_diff($toppings1, $toppings2);

    var_dump($diff_toppings);
    // prints: array(3) { [0]=> string(9) "Pepperoni" [2]=>
    // string(9) "Anchovies" [3]=> string(8) "Tomatoes" }

You can diff several arrays simultaneously by providing more parameters to the function. In this situation, the function will return an array of values in the first array that do not appear in the second and subsequent arrays. For example:

    $arr1_unique = array_merge($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.