In this tutorial, you shall learn about PHP array_diff_key() function which can compute the difference of an array against other arrays based on keys, with syntax and examples.
PHP array_diff_key() Function
PHP array_diff_key() function computes the difference of an array against other arrays based on keys. Only key/index of the arrays is used for comparison.
In this tutorial, we will learn the syntax of array_diff_key(), and how to use this function to find the difference of an array from other arrays based on keys, covering different scenarios based on array type and arguments.
Syntax of array_diff_key()
The syntax of PHP array_diff_key() function is
array_diff_key ( array $array1 , array $array2 [, array $... ] ) : array
where
| Parameter | Description |
|---|---|
| array1 | [mandatory] Array of interest. Compare the keys/index of this array against other arrays’. |
| array2 | [mandatory] Array of reference. The keys of this array are used to comparison against. |
Along with array2, you can provide as many number of arrays to compare against. But these additional arrays are optional.
Return Value
The array_diff_key() function returns an array of elements whose keys are present in $array1 but not present in $array2 or other arrays(if provided).
Examples
1. Compute difference of Arrays based on keys: array1 – array2
In this example, we will take an associative array, array1, with key-value pairs, compare it against another array array2, and find their difference using array_diff_key() function.
PHP Program
<?php
$array1 = array('a'=>'apple', 'b'=>'banana', 'c'=>'cherry');
$array2 = array('a'=>'apricot', 'c'=>'cherry');
$result = array_diff_key($array1, $array2);
print_r($result);
?>
Output
