In PHP, the array_diff_key() function is used to compare two or more arrays, returning parts of the first array that are different from other array keys. It is used in the following form:
array_diff_key(array $array1, array $array2, array ...$arrays): array
The result returned by this function is: all keys in the first array do not appear in other arrays . That is, it will appear in the result only if a key does not exist in other arrays.
But if an empty array is passed in, the behavior of the function will cause some special phenomena. Let's discuss what kind of return value array_diff_key() will have when passing in an empty array.
$array1 = ["a" => 1, "b" => 2, "c" => 3];
$array2 = [];
$result = array_diff_key($array1, $array2);
print_r($result);
Array
(
[a] => 1
[b] => 2
[c] => 3
)
When the second array $array2 is an empty array, array_diff_key() will directly return all key-value pairs of the first array $array1 . The reasons are as follows:
The principle of array_diff_key() is to return an array based on the difference in keys.
If the second array is empty, then it has no keys to compare with the keys in the first array. Therefore, all keys in the first array will not be found in the second array.
So array_diff_key() will return all key-value pairs of the first array, because they are "unlike anything".
From this example, we can see that if the second array is empty, array_diff_key() will not make any comparisons and will directly return the first array.
If multiple arrays are passed in, there are empty arrays, the behavior of array_diff_key() is still to return keys in the first array that are not in the other arrays. For example:
$array1 = ["a" => 1, "b" => 2, "c" => 3];
$array2 = [];
$array3 = ["a" => 100];
$result = array_diff_key($array1, $array2, $array3);
print_r($result);
Execution results:
Array
(
[b] => 2
[c] => 3
)
In this example, the key "a" in the first array $array1 exists in the third array $array3 , so "a" does not appear in the return result. And "b" and "c" are not found in $array3 , so they will be preserved.
When an empty array is passed to array_diff_key() , all elements of the first array will be returned.
An empty array has no keys compared to other arrays, so it is considered that all keys do not appear in other arrays.
If multiple arrays are passed in, and there are empty arrays, the behavior of array_diff_key() will still return the result based on the actual compared array.