Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_diff() function

Reference for PHP array_diff(): find values present in one array but missing from others, with string comparison, kept keys and common mistakes.

array_diff() compares the first array with one or more others and returns the values from the first array that do not appear in any of the others. It answers questions like "which items were removed?" or "which ids are not yet processed?".

Only values are compared, and the comparison is done on their string form. The keys of the first array are preserved in the result.

PHP
<?php
print_r(array_diff([1, 2, 3, 4], [2, 4])); // [0 => 1, 2 => 3]

Try it

PHP Values missing from other arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP String comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_diff(array $array, array ...$arrays): array
Name Description
$array The array to compare from. Its values are the candidates for the result.
...$arrays One or more arrays to compare against.

Return value: an array of the values from $array that are in none of the other arrays, with the keys of $array preserved.

Usage notes

  • Values are compared as strings ((string) $a === (string) $b). 1 and "1" match; "1.0" and 1 do not.
  • Order matters. array_diff($a, $b) is not the same as array_diff($b, $a). For both directions, merge the two results, as in the second example.
  • Keys are kept, so the result can have gaps. Apply array_values() for a clean list.
  • Nested arrays are not supported in values; they cause an "Array to string conversion" warning. Use array_udiff() with your own comparison for rows.
  • Compare keys instead with array_diff_key() and array_diff_assoc().
  • The opposite operation is array_intersect().
  • Performance: for large arrays, flipping the second array and testing with isset() (see array_flip()) can be faster than repeated array_diff() calls with many values.