PHP array_diff() Function
Topic: PHP Array ReferencePrev|Next
Description
The array_diff()
function compares the values of two or more arrays and returns the differences.
The following table summarizes the technical details of this function.
Return Value: | Returns an array containing all the elements from array1 that are not present in any of the other arrays. |
---|---|
Version: | PHP 4.0.1+ |
Syntax
The basic syntax of the array_diff()
function is given with:
The following example shows the array_diff()
function in action.
Example
Run this code »<?php
// Sample arrays
$array1 = array("apple", "ball", "cat", "dog", "elephant");
$array2 = array("alligator", "dog", "elephant", "lion", "cat");
// Computing the difference
$result = array_diff($array1, $array2);
print_r($result);
?>
Parameters
The array_diff()
function accepts the following parameters.
Parameter | Description |
---|---|
array1 | Required. Specifies the array to compare from. |
array2 | Required. Specifies an array to compare against. |
... | Optional. Specifies more arrays to compare against. |
More Examples
Here're some more examples showing how array_diff()
function actually works:
The following example shows how to use this function to compare an array against two other arrays.
Example
Run this code »<?php
// Sample arrays
$array1 = array("apple", "ball", "cat", "dog");
$array2 = array("cat", "lion", "tiger");
$array3 = array("apple", "banana");
// Computing the difference
$result = array_diff($array1, $array2, $array3);
print_r($result);
?>
Two elements are considered equal if their string representation are same, i.e., (string) $elem1 === (string) $elem2. Let's take a look at the following example:
Example
Run this code »<?php
// Sample arrays
$array1 = array(1, 2, 5, 7, 11);
$array2 = array(0, "1", 2, 4, "07", 10);
// Computing the difference
$result = array_diff($array1, $array2);
print_r($result);
?>
You can also use associative arrays, however the keys are not considered in the comparison.
Example
Run this code »<?php
// Sample arrays
$array1 = array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow");
$array2 = array("x"=>"black", "y"=>"blue", "z"=>"red");
// Computing the difference
$result = array_diff($array1, $array2);
print_r($result);
?>