English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP array_diff_key() Function Usage and Example

PHP Array Function Manual

Definition and Usage

The array_diff_key() function uses key name comparison to calculate the difference set of arrays, taking array1keys are compared with array2, array3 ... are compared, and the array with differences is returned. In array1is available while the keys in array2, array3are not available in the array. This function is similar to array_diff() function, but the comparison is based on keys rather than values.

Syntax

array array_diff_key(array $array1, array $array2 [, array $...];

Parameter

Serial NumberParameters and Description
1

array1(Required)

to be compared.

2

array2(Required)

It is an array to be compared with the first array

3

array3(Optional)

It is an array to be compared with the first array

Return Value

 array_diff_key() returns an array that includes all keys that appear in the array1 but did not appear in any other parameter arrays, the values of the key names.

PHP version

This function was introduced in PHP version5.1.0 was first introduced

Online Example

This example returns4and5values, because the first three keys (0,1and2) are the same in the two arrays, even though their values are different

<?php
   $input1 = array(1, 2, 3, 4, 5);
   $input2 = array(4, 5, 6);
   $result = array_diff_key($input1, $input2);
   print_r($result);
?>
Test and See‹/›

Output Result:

Array
(
    [3] => 4
    [4] => 5
)

Online Example

This example returns an empty array because array_diff_key() compares keys rather than values, as it finds that both arrays have the same keys, even though the values are different, so no differences are found, and an empty array is returned

<?php
   $input4 = array(1, 2, 3);
   $input5 = array(4, 5, 6);
 
   $result = array_diff_key($input4, $input5);
   print_r($result);
?>
Test and See‹/›

Output Result:

Array
(
)

Online Example

The following examples demonstrate the use of the array_diff_key() array function-

<?php
   $input1 = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow", "f"=>"yellow");
   $input2 = array("a"=>"red","b"=>"green","c"=>"blue");
   $result = array_diff_key($input1, $input2);
   print_r($result);
?>
Test and See‹/›

Output Result:

Array
(
    [d] => yellow
    [f] => yellow
)

PHP Array Function Manual