array_diff_key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

array_diff_key使用键名比较计算数组的差集

说明

array_diff_key(array $array, array ...$arrays): array

根据 array 中的键名和 arrays 进行比较,返回不同键名的项。 本函数和 array_diff() 相同只除了比较是根据键名而不是值来进行的。

参数

array

从这个数组进行比较

arrays

要进行比较的数组

返回值

返回一个数组,该数组包含了所有出现在 array 中但是未出现在任何其它数组中的键名的值。

更新日志

版本 说明
8.0.0 现在可以仅使用一个参数调用此函数。以前,至少需要两个参数。

示例

示例 #1 array_diff_key()

key => value 对中的两个键名仅在 (string) $key1 === (string) $key2 时被认为相等。换句话说,执行的是严格类型检查,因此字符串的表达必须完全一样。

<?php
$array1
= array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'yellow' => 7, 'cyan' => 8);

var_dump(array_diff_key($array1, $array2));
?>

以上示例会输出:

array(3) {
  ["blue"]=>
  int(1)
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}
<?php
$array1
= array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'yellow' => 7, 'cyan' => 8);
$array3 = array('blue' => 6, 'yellow' => 7, 'mauve' => 8);

var_dump(array_diff_key($array1, $array2, $array3));
?>

以上示例会输出:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

注释

注意:

注意本函数只检查了多维数组中的一维。当然,可以用 array_diff_key($array1[0], $array2[0]); 来检查更深的维度。

参见

add a note add a note

User Contributed Notes 11 notes

up
17
Ashton
16 years ago
To return the unique elements (those with a key that exists only once in either array but not in both) try:
function array_unique_diff ($array1, $array2)
{
  array_merge(array_diff_key($array1, $array2), array_diff_key($array2, $array1));
}

Example:
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

  array_diff_key($array1, $array2)

returns

  array ( 'red' => 2, 'purple' => 4 )

  array_diff_key($array2, $array1)

returns

  array ( 'yellow' => 7, 'cyan' => 8, )

  array_unique_diff($array1, $array2);
 
returns

  array ( 'red' => 2, 'purple' => 4, 'yellow' => 7, 'cyan' => 8, )
up
5
gk at anuary dot com
11 years ago
Improved recursive version.

<?php
/**
* @author Gajus Kuizinas <gk@anuary.com>
* @version 1.0.0 (2013 03 19)
*/
function array_diff_key_recursive (array $arr1, array $arr2) {
   
$diff = array_diff_key($arr1, $arr2);
   
$intersect = array_intersect_key($arr1, $arr2);
   
    foreach (
$intersect as $k => $v) {
        if (
is_array($arr1[$k]) && is_array($arr2[$k])) {
           
$d = array_diff_key_recursive($arr1[$k], $arr2[$k]);
           
            if (
$d) {
               
$diff[$k] = $d;
            }
        }
    }
   
    return
$diff;
}
?>

An up to date version is maintained at https://github.com/gajus/flow/blob/master/flow.inc.php#L337.
up
5
sjungwirth at matrix-consultants dot com
16 years ago
I needed something a little different where maybe even the keys in multidimensional arrays don't match up. Setting $assoc to false will cause only to check for missing keys, otherwise it compares values as well. This was also based on '2ge at 2ge dot us' function

<?php

function n_array_diff_assoc ($a1, $a2, $assoc=true) {
   
$r = array();
    if(
is_array(current($a1))):
        foreach(
$a1 as $k => $v):
            if(isset(
$a2[$k])):
               
$diff = n_array_diff($a1[$k], $a2[$k], $assoc);
                if (!empty(
$diff)):
                   
$r[$k] = $diff;
                endif;
            else:
               
$r[$k] = $v;
            endif;
        endforeach;
    else:
       
$r = $assoc ? array_diff_assoc($a1, $a2) : array_diff_key($a1, $a2);
    endif;
    return
$r;
}
?>
up
6
maxence at pontapreta dot net
19 years ago
Seems to be a great function, especially for n-dimensions arrays. The only problem is that I cannot find it in php 5.0.3 and 5.0.4. Does it really exist ?! :(

[20:27:05][maxence@conurb] ~/test2/php-5.0.4$ grep PHP_FUNCTION * -r | grep -i array_diff_key
[20:27:09][maxence@conurb] ~/test2/php-5.0.4$
up
3
AiFiLTr0 [at host] invyl [dot] ath.cx
16 years ago
The recursive function suggested by '2ge at 2ge dot us' will provide you with empty arrays if there's no diff.
This variant of the function cleans up empty arrays and fixes a bug in the first suggested version. It works 100%
.
<?php
function array_diff_key_recursive ($a1, $a2) {
        foreach(
$a1 as $k => $v) {
           
//$r[$k] = is_array($v) ? $this->array_diff_key_recursive($a1[$k], $a2[$k]) : array_diff_key($a1, $a2);
       
if (is_array($v))
            {
           
$r[$k]=$this->array_diff_key_recursive($a1[$k], $a2[$k]);
            }else
            {
           
$r=array_diff_key($a1, $a2);
            }

        if (
is_array($r[$k]) && count($r[$k])==0)
            {
            unset(
$r[$k]);
            }
        }
        return
$r;
    }
?>
up
3
coder at gs dot com
16 years ago
The PHP4 version below works only unidirectionally. If you switch the arrays around i.e. (ar2, ar1) you get different results than (ar1, ar2).
up
0
ampf at egp dot up dot pt
18 years ago
Well, you could implement in the code something more powerfull:

http://www.php.net/manual/en/function.array-diff.php#31364
up
-2
division-par-zero at zilon dot net
16 years ago
you can use this function for return the difference of two array !

<?php
function array_unique_diff_key ($array1, $array2)
{
  if (
is_array($array1) && is_array($array2))
    return
array_diff_key($array1, $array2) + array_diff_key($array2, $array1);
  else if (
is_array($array1)) return $array1;
  else if (
is_array($array2)) return $array2;
  else return array();
}
?>
up
-3
vlad_mustafin at ukr dot net
18 years ago
One more alternative variant :)
<?
if (!function_exists('array_diff_key')) {
    function
array_diff_key() {
       
$argCount   = func_num_args();
       
$diff_arg_prefix = 'diffArg';
       
$diff_arg_names = array();
        for (
$i=0; $i < $argCount; $i++) {
           
$diff_arg_names[$i] = 'diffArg'.$i;
            $
$diff_arg_names[$i] = array_keys((array)func_get_arg($i));
        }
       
$diffArrString = '';
        if (!empty(
$diff_arg_names)) $diffArrString '$'.implode(', $', $diff_arg_names);
        eval(
"\$result = array_diff(".$diffArrString.");");
        return
$result;
    }
}
?>
up
-2
rhallsey at yahoo dot com
10 years ago
Here's a simple function that returns true if all keys in the first array are found in the second array, and false if they aren't.

function same_keys ($a1, $a2) {
    $same = false;
    if (!array_diff_key($a1, $a2)) {
        $same = true;
        foreach ($a1 as $k => $v) {
            if (is_array($v) && !same_keys($v, $a2[$k])) {
                $same = false;
                break;
            }
        }
    }
    return $same;
}

To check if two arrays have the same structure, ignoring values, execute the function twice, the second time with the arguments reversed.
up
-5
2ge at 2ge dot us
18 years ago
Hello, if you need diff key of n-dimensional arrays here is nice solution:
<?php
function n_array_diff ($a1, $a2) {
        foreach(
$a1 as $k => $v) {
           
$r[$k] = is_array($v) ? n_array_diff($a1[$k], $a2[$k]) : array_diff_key($a1, $a2);
        }
        return
$r;
}
?>
it will print everything, what is missing in $a2.
To Top