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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using array_diff_key() to Compute Array Differences by Keys in PHP

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().

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendprogrammingPHPArrayTutorialarray_diff_key
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.