PHP array_diff_key() Function

The array_diff_key() function compares the keys of two or more arrays and returns the key-value pairs from the first array whose keys are not present in the other arrays.

Version Support: array_diff_key() in PHP 8.5, array_diff_key() in PHP 8.4, array_diff_key() in PHP 8.3, array_diff_key() in PHP 8.2, array_diff_key() in PHP 8.1, array_diff_key() in PHP 7.1, array_diff_key() in PHP 7.2, array_diff_key() in PHP 7.3, array_diff_key() in PHP 7.4

Syntax

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

→The first array is the one being compared.
→Any additional arrays are checked for matching keys.
→Values are ignored; only keys are compared.

The function returns a new array and does not modify the input arrays.

Example

<?php
$array1 = [
   "name" => "Mia",
   "age"  => 28,
   "city" => "Paris"
];

$array2 = [
   "age" => 35,
   "country" => "France"
];

$result = array_diff_key($array1, $array2);

print_r($result);

?>

Output:

Array
(
   [name] => Mia
   [city] => Paris
)

The key "age" is excluded because it also exists in $array2, even though its value is different.

4 Views