array_diff_key() function use in PHP 8.4 With Example

The array_diff_key() function in PHP 8 compares arrays by their keys and returns the difference. It checks the keys of the first array against subsequent arrays and returns an array containing entries from the first array whose keys are not present in the other arrays. Here’s how to use it:

Syntax

array_diff_key(array $array1, array $array2, array …$arrays): array

Key Features in PHP 8

  1. Strict Type Checks: PHP 8 enforces stricter type handling. If non-array arguments are passed, a TypeError is thrown.
  2. No Deprecations: Works the same as in PHP 7 but with stricter error handling.
  3. Performance: Optimized for PHP 8’s engine.

Basic Example

$array1 = ['name' => 'Alice', 'age' => 30, 'city' => 'Paris'];
$array2 = ['age' => 25, 'country' => 'France'];
$result = array_diff_key($array1, $array2);
print_r($result);

Output:

Array
(
[name] => Alice
[city] => Paris
)
  • The keys name and city from $array1 are absent in $array2, so they are returned.

Edge Cases

  1. Multiple Arrays
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['a' => 4];
$array3 = ['c' => 5];
$result = array_diff_key($array1, $array2, $array3);
print_r($result); // Output: ['b' => 2]
  1. Empty Arrays
$array1 = ['key' => 'value'];
$array2 = [];
$result = array_diff_key($array1, $array2);
print_r($result); // Output: ['key' => 'value']

PHP 8 Error Handling

PHP 8 throws a TypeError if non-array arguments are passed:

// This will throw a TypeError in PHP 8
$result = array_diff_key(['a' => 1], 'not_an_array');

Fix:

if (is_array($input)) {
$result = array_diff_key(['a' => 1], $input);
}