Using array_diff_key() to Compute Array Differences by Keys in PHP
This article explains how the PHP function array_diff_key() compares arrays by their keys, describes its parameters and return value, and provides a complete example with code and output showing how to obtain the key‑based difference between two associative arrays.
The array_diff_key() function compares the keys of one array against one or more other arrays and returns the entries from the first array whose keys are not present in any of the subsequent arrays. It works similarly to array_diff() but uses key comparison instead of value comparison.
Function signature : array_diff_key(array $array1, array $array2, ... $arrayN) Parameters
array1 : The array to compare against the others.
array2 , arrayN : One or more arrays whose keys will be used for comparison.
Return value
The function returns an array containing all key‑value pairs from $array1 whose keys do not appear in any of the other supplied arrays.
Example
<?php
$array1 = array(
'blue' => 1,
'red' => 2,
'green' => 3,
'purple' => 4
);
$array2 = array(
'green' => 5,
'blue' => 6,
'yellow' => 7,
'cyan' => 8
);
var_dump(array_diff_key($array1, $array2));
?>Output
array(2) {
["red"]=> int(2)
["purple"]=> int(4)
}This output shows that the keys red and purple exist in $array1 but not in $array2, so they are returned by array_diff_key().
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
