array_diff
Returns the values of the first array that are absent from the others.
Syntax
array_diff(array $array, array ...$arrays): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array to take values from. |
| ...$arrays | array | The arrays to compare against. |
Return value
arrayThe values present only in the first array.
Examples
What is left to buy:
<?php
$need = ['milk', 'bread', 'tea'];
$bought = ['bread'];
echo implode(', ', array_diff($need, $bought));Output:
milk, teaRemoving values from a list:
<?php
echo implode(', ', array_diff([1, 2, 3, 4, 5], [2, 4]));Output:
1, 3, 5Notes
The keys of the first array are preserved. Values are compared as strings: 1 and '1' count as equal.
See also
- array_intersect — Returns the values present in every array.
- array_unique — Removes duplicate values from an array.
Related recipes
In the tutorial
- Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.