PHP array_diff() Function
The array_diff()
function is an inbuilt function in PHP that compares two or more arrays and returns the differences, considering values only (not keys). This function was introduced in PHP 4.0.
Syntax
array array_diff ( array $array1 , array $array2 [, array $... ] );
Parameters
Parameter | Description | Is Compulsory |
---|---|---|
array1 | The first array to compare. | Compulsory |
array2 | The array to compare against. | Compulsory |
... | Additional arrays to compare against. | Optional |
Return Values
The array_diff()
function returns an array containing all the values from array1
that are not present in any of the other arrays.
PHP Example
<?php
$array1 = array("red", "green", "blue", "yellow");
$array2 = array("red", "blue", "pink");
print_r(array_diff($array1, $array2));
?>
Output
Array
(
[1] => green
[3] => yellow
)
(
[1] => green
[3] => yellow
)
PHP Example
<?php
$array1 = array("apple", "banana", "cherry", "date");
$array2 = array("banana", "date", "fig");
$array3 = array("apple", "fig");
print_r(array_diff($array1, $array2, $array3));
?>
Output
Array
(
[2] => cherry
)
(
[2] => cherry
)