PHP array_diff() function
Syntax
PHP array_diff() function has the following syntax
array array_diff ( array arr1, array arr2 [, array ...] )
Description
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
Parameter | Is required | Description |
---|---|---|
array1 | Required. | The array to compare from |
array2 | Required. | An array to compare against |
array3,... | Optional. | More arrays to compare against |
Example 1
Find the difference between two arrays
<?PHP//ww w .j a v a2 s.c o m
$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// w w w. j a v a 2 s .co m
$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.