Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_diff

Returns the values of the first array that are absent from the others.

Syntax

array_diff(array $array, array ...$arrays): array

Parameters

ParameterTypeDescription
$arrayarrayThe array to take values from.
...$arraysarrayThe 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, tea

Removing values from a list:

<?php
 
echo implode(', ', array_diff([1, 2, 3, 4, 5], [2, 4]));

Output:

1, 3, 5

Notes

The keys of the first array are preserved. Values are compared as strings: 1 and '1' count as equal.

See also

Related recipes

In the tutorial

  • Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.

Thanks for reading!

Donate to the site — we work hard for you.