Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_diff_key() and array_diff_assoc() functions

Reference for PHP array_diff_key() and array_diff_assoc(): compare arrays by key or by key and value, keep the first array's keys, and avoid common traps.

array_diff_key() returns the entries of the first array whose keys do not appear in any of the other arrays. The values are ignored completely. array_diff_assoc() is stricter: an entry is removed only when both the key and the value match an entry in another array.

Both functions keep the keys of the first array and its order, and they never change their arguments. Compare them with array_diff(), which looks at values only.

PHP
<?php
$all = ["a" => 1, "b" => 2, "c" => 3];
print_r(array_diff_key($all, ["a" => 0]));
// ["b" => 2, "c" => 3]

Try it

PHP Removing keys you do not want

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 Key only versus key and value

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_key(array $array, array ...$arrays): array
array_diff_assoc(array $array, array ...$arrays): array
Name Description
$array The array to filter. Its keys and order are kept in the result.
...$arrays One or more arrays to compare against.

Return value: an array with the entries of $array that have no match in any of the other arrays.

Usage notes

  • array_diff_key() ignores values. Only the key decides whether an entry is removed. A value of null or false in the other array still counts as "the key is present".
  • array_diff_assoc() needs both to match. Keys are compared strictly, and values are compared as strings ((string) $a === (string) $b), so "1" and 1 match, but "1.0" and 1 do not.
  • Direction matters. array_diff_key($a, $b) is not the same as array_diff_key($b, $a). Run it twice for a symmetric difference.
  • Numeric keys are compared as keys, not as positions. In array_diff_key([10, 20, 30], [1 => 0]) the entry at key 1 disappears and the others keep keys 0 and 2.
  • Custom comparison: the array_diff_ukey(), array_udiff() and array_udiff_assoc() variants take callbacks. array_diff_uassoc() compares keys with your callback.
  • Typical use: stripping unwanted fields from request data, or reporting which settings changed between two configurations.
  • Nested arrays are compared as strings and produce an "Array to string conversion" warning. Compare nested structures yourself.