In PHP, array_intersect_key and array_diff_key are both array handling functions used to compare the keys of arrays, but their behaviors and purposes differ. In this article, we will discuss their differences in detail and help you better understand their usage scenarios through practical examples.
The array_intersect_key function returns the keys and corresponding values that exist in all of the arrays provided. In other words, it returns a new array containing elements whose keys are present in every array being compared.
array array_intersect_key(array $array1, array $array2, array ...$arrays)
$array1: The first array to compare.
$array2: The second array to compare.
$arrays: Optional additional arrays to compare.
<?php
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['b' => 4, 'c' => 5, 'd' => 6];
<p>$result = array_intersect_key($array1, $array2);<br>
print_r($result);<br>
?><br>
Array
(
[b] => 2
[c] => 3
)
In this example, array_intersect_key returns the elements from $array1 whose keys b and c are also present in $array2. Therefore, the result contains the values of these two keys.
The array_diff_key function returns an array containing the key-value pairs from the first array that are not present in the other arrays. Its purpose is to remove keys from the first array that also exist in the subsequent arrays.
array array_diff_key(array $array1, array $array2, array ...$arrays)
$array1: The first array to compare with others.
$array2: The second array to compare.
$arrays: Optional additional arrays to compare.
<?php
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['b' => 4, 'c' => 5, 'd' => 6];
<p>$result = array_diff_key($array1, $array2);<br>
print_r($result);<br>
?><br>
Array
(
[a] => 1
)
In this example, array_diff_key returns the element with the key a from $array1, because this key does not exist in $array2.
The key difference between array_intersect_key and array_diff_key is:
array_intersect_key returns key-value pairs that exist in all arrays.
array_diff_key returns key-value pairs that exist in the first array but not in the others.
Suppose you have three arrays:
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['b' => 4, 'c' => 5, 'd' => 6];
$array3 = ['c' => 7, 'd' => 8];
array_intersect_key($array1, $array2, $array3) will return ['c' => 3], because the key c exists in all arrays.
array_diff_key($array1, $array2, $array3) will return ['a' => 1, 'b' => 2], because keys a and b exist only in $array1, not in $array2 or $array3.
array_intersect_key is used to find keys that are present in multiple arrays and returns those keys along with their values.
array_diff_key is used to find keys that exist in the first array but are missing from the subsequent arrays, returning those keys and their values.
Both functions are very useful in array operations, especially when you need to compare and filter based on keys. Understanding their differences will help you handle PHP arrays more efficiently.