PHP Tutorial - PHP array_diff() function


PHP array_diff() function has the following syntax

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.

You can diff several arrays by providing more parameters. 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_diff($array1, $array2, $array3, $array4);


ParameterIs requiredDescription
array1Required.The array to compare from
array2Required.An array to compare against
array3,...Optional.More arrays to compare against

Example 1

Find the difference between two arrays

$toppings1 = array("A", "B", "C", "D");
$toppings2 = array("C", "D", "");
$diff_toppings = array_diff($toppings1, $toppings2);


The code above generates the following result.

Example 2

Different two associative arrays

$a3=array("a"=>"Apple","b"=>"New B","h"=>"Help");


The code above generates the following result.