PHP array_diff() Function
Example
Compare the keys and values of two arrays and return the difference set:
<?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"green","g"=>"blue"); $result=array_diff($a1,$a2); print_r($result); ?>
Definition and Usage
The array_diff() function returns an array of the difference set of two arrays. This array includes all the keys in the arrays being compared, but not in any other parameter array.
The key names remain unchanged in the returned array.
Syntax
array_diff(array1,array2,array3...);
Parameter | Description |
---|---|
array1 | Required. The first array to compare with other arrays. |
array2 | Required. The array to compare with the first array. |
array3,... | Optional. Other arrays to compare with the first array. |
Tips and Notes
Tip:You can use one or any number of arrays to compare with the first array.
Note:Only values are used for comparison.
Technical Details
Return Value: | Return the difference set array, which includes all the keys in the arrays being compared(array1)in, but not in any other parameter array(array2 or array3 etc.) keys. |
PHP Version: | 4.0.1+ |
More Examples
Example 1
Compare the values of three arrays and return the difference set:
<?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"black","g"=>"purple"); $a3=array("a"=>"red","b"=>"black","h"=>"yellow"); $result=array_diff($a1,$a2,$a3); print_r($result); ?>