In PHP, array_diff_key() is a function used to calculate the difference set of two arrays. It returns an array containing all key-value pairs that exist in the first array but not in the second array. This function compares based on the keys of the array, not the values.
array_diff_key(array $array1, array $array2, array ...$arrays): array
$array1
This is the first array to be compared.
$array2
This is the second array to be compared with $array1 . The keys in this array will be removed from $array1 .
$arrays (optional)
More arrays can be passed for comparison, array_diff_key() will remove keys from these arrays from $array1 .
This function returns a new array containing all key-value pairs that exist in $array1 but not in $array2 or other passed arrays.
Here is an example using the array_diff_key() function:
<?php
$array1 = [
"apple" => 1,
"banana" => 2,
"cherry" => 3
];
$array2 = [
"banana" => 2,
"cherry" => 3
];
$result = array_diff_key($array1, $array2);
print_r($result);
?>
Output:
Array
(
[apple] => 1
)
In this example, array_diff_key() compares $array1 and $array2 and returns a new array containing the key "apple" , because this key only exists in $array1 and not in $array2 .
You can also pass multiple arrays to array_diff_key() , which compares the keys in $array1 and all other arrays, returning key-value pairs that contain key-values that exist in $array1 but are not in other arrays.
<?php
$array1 = [
"apple" => 1,
"banana" => 2,
"cherry" => 3,
"date" => 4
];
$array2 = [
"banana" => 2,
"cherry" => 3
];
$array3 = [
"apple" => 1,
"date" => 4
];
$result = array_diff_key($array1, $array2, $array3);
print_r($result);
?>
Output:
Array
(
[banana] => 2
)
In this example, array_diff_key() compares $array1 and $array2 , $array3 , and returns an array containing the key "banana" because it only appears in $array1 , but in $array2 and $array3 .
array_diff_key() is a key-based comparison, not a value. So it doesn't take into account the values in the array, it just operates on the keys.
If you pass multiple arrays, the function compares the keys of those arrays and returns an array containing the unique keys in $array1 .
If a key is present in all arrays, the result will not contain this key.
If you want to see more detailed documentation on the array_diff_key() function, refer to the following link: