PHP Function Reference

PHP array_diff() Function



The PHP array_diff() function compares values of an array against one or more other arrays and returns all elements of the first array that are not present in any of the other arrays.

The array_diff_key() function is like this function except the comparison is done on the keys instead of the values.

Syntax

array_diff(array, arrays)

Parameters

array Required. Specify an array to compare from.
arrays Required. Specify one or more arrays to compare against.

Return Value

Returns an array containing all the entries from array that are not present in any of the other arrays. Keys in the given array are preserved.

Exceptions

NA.

Example:

The example below shows the usage of array_diff() function.

<?php
$Arr1 = array(10, 20, 30, 40, "Hello", "World");
$Arr2 = array(10, 20, 30);
$Arr3 = array("Hello", "John");

//comparing Arr1 against Arr2
$Arr1_diff_Arr2 = array_diff($Arr1, $Arr2);
print_r($Arr1_diff_Arr2);

echo "\n";

//comparing Arr1 against Arr2 and Arr3
$Arr1_diff_All = array_diff($Arr1, $Arr2, $Arr3);
print_r($Arr1_diff_All);
?>

The output of the above code will be:

Array
(
    [3] => 40
    [4] => Hello
    [5] => World
)

Array
(
    [3] => 40
    [5] => World
)

Example:

Consider the example below where array_diff() function is used with associative arrays. Please note that, multiple occurrences in Arr1 are all treated the same way.

<?php
$Arr1 = array("a"=>"Red",
              "b"=>"Red",
              "c"=>"Blue",
              "d"=>"Blue",
              "e"=>"Green");
$Arr2 = array("p"=>"Red", 
              "q"=>"Black", 
              "r"=>"White");

//comparing Arr1 against Arr2
$Arr1_diff_Arr2 = array_diff($Arr1, $Arr2);
print_r($Arr1_diff_Arr2);
?>

The output of the above code will be:

Array
(
    [c] => Blue
    [d] => Blue
    [e] => Green
)

❮ PHP Array Reference