PHP array_diff_key() function

Example

Compare the keys of two arrays and return the difference set:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"red","c"=>"blue","d"=>"pink");
$result=array_diff_key($a1,$a2);
print_r($result);
?>

Run Instances

Definition and Usage

The array_diff_key() function is used to compare the keys of two (or more) arrays and returns the difference set.

The function compares the keys of two (or more) arrays and returns a difference set array that includes all the elements that are in the compared arrays (array1In, but not in any other parameter array (array2 or array3 etc.) key names.

Description

The array_diff_key() function returns an array that includes all the keys that are in the compared arrays but not in any other parameter arrays.

Syntax

array_diff_key(array1,array2,array3...);
Parameters Description
array1 Required. The first array to be compared with other arrays.
array2 Required. The array to be compared with the first array.
array3,... Optional. Other arrays to compare with the first array.

Technical Details

Return Value: Returns an array that contains all the array1 but not in any other parameter array (array2 or array3 etc.) key names.
PHP Version: 5.1+

More Examples

Example 1

Compare the key names of two numeric arrays and return the difference set:

<?php
$a1=array("red","green","blue","yellow");
$a2=array("red","green","blue");
$result=array_diff_key($a1,$a2);
print_r($result);
?>

Run Instances

Example 2

Compare the key names of three arrays and return the difference set:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("c"=>"yellow","d"=>"black","e"=>"brown");
$a3=array("f"=>"green","c"=>"purple","g"=>"red");
$result=array_diff_key($a1,$a2,$a3);
print_r($result);
?>

Run Instances