PHP Tutorial - PHP array_diff() function






Syntax

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);

Parameter

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


<?PHP
$toppings1 = array("A", "B", "C", "D");
$toppings2 = array("C", "D", "java2s.com");
$diff_toppings = array_diff($toppings1, $toppings2);

var_dump($diff_toppings);
?>

The code above generates the following result.

Example 2

Different two associative arrays


<?php
$a1=array("a"=>"A","b"=>"B","c"=>"C","j"=>"java2s.com");
$a2=array("e"=>"E","f"=>"F","g"=>"Good");
$a3=array("a"=>"Apple","b"=>"New B","h"=>"Help");

$result=array_diff($a1,$a2,$a3);
print_r($result);
?>

The code above generates the following result.