downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

array_diff_uassoc> <array_diff_assoc
[edit] Last updated: Fri, 24 May 2013

view this page in

array_diff_key

(PHP 5 >= 5.1.0)

array_diff_keyCalcule la différence de deux tableaux en utilisant les clés pour comparaison

Description

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

Compare les clés du tableau array1 avec les clés du tableau array2 et retourne la différence. Cette fonction est identique à la fonction array_diff(), excepté sur le fait que la comparaison est faite sur les clés, plutôt que sur les valeurs.

Liste de paramètres

array1

Le tableau à comparer

array2

Le tableau à comparer

...

Plus de tableaux à comparer

Valeurs de retour

Retourne un tableau contenant toutes les entrées du tableau array1 dont les clés ne sont présentes dans aucun des autres tableaux.

Exemples

Exemple #1 Exemple avec array_diff_key()

Les deux clés depuis les paires clé => valeur sont considérées comme égales uniquement si (string) $cle1 === (string) $cle2 . En d'autres termes, une analyse de type stricte est exécutée, donc, le type doit être exactement le même.

<?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));
?>

L'exemple ci-dessus va afficher :

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

Notes

Note:

Notez que cette fonction vérifie uniquement une dimension d'un tableau possédant n dimensions. Bien sûr, vous pouvez vérifier une dimension plus profonde en utilisant, par exemple, array_diff_key($array1[0], $array2[0]);.

Voir aussi

  • array_diff() - Calcule la différence entre des tableaux
  • array_udiff() - Calcule la différence entre deux tableaux en utilisant une fonction rappel
  • array_diff_assoc() - Calcule la différence de deux tableaux, en prenant aussi en compte les clés
  • array_diff_uassoc() - Calcule la différence entre deux tableaux associatifs, à l'aide d'une fonction de rappel
  • array_udiff_assoc() - Calcule la différence entre des tableaux avec vérification des index, compare les données avec une fonction de rappel
  • array_udiff_uassoc() - Calcule la différence de deux tableaux associatifs, compare les données et les index avec une fonction de rappel
  • array_diff_ukey() - Calcule la différence entre deux tableaux en utilisant une fonction de rappel sur les clés pour comparaison
  • array_intersect() - Calcule l'intersection de tableaux
  • array_intersect_assoc() - Calcule l'intersection de deux tableaux avec des tests sur les index
  • array_intersect_uassoc() - Calcule l'intersection de deux tableaux avec des tests sur les index, compare les index en utilisant une fonction de rappel
  • array_intersect_key() - Calcule l'intersection de deux tableaux en utilisant les clés pour comparaison
  • array_intersect_ukey() - Calcule l'intersection de deux tableaux en utilisant une fonction de rappel sur les clés pour comparaison



array_diff_uassoc> <array_diff_assoc
[edit] Last updated: Fri, 24 May 2013
 
add a note add a note User Contributed Notes array_diff_key - [15 notes]
up
2
Ashton
5 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
1
division-par-zero at zilon dot net
4 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
1
sjungwirth at matrix-consultants dot com
5 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
1
AiFiLTr0 [at host] invyl [dot] ath.cx
5 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
1
ampf at egp dot up dot pt
7 years ago
Well, you could implement in the code something more powerfull:

http://www.php.net/manual/en/function.array-diff.php#31364
up
4
maxence at pontapreta dot net
7 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
2
2ge at 2ge dot us
7 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.
up
1
coder at gs dot com
5 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
ml at iceni dot pl
7 years ago
You may obtain this function with PEAR Package PHP_Compat (http://pear.php.net/package/PHP_Compat)

Then using such code is quite useful
<?php
if(!function_exists('array_diff_key')){
    require_once
'PHP/Compat/Function/array_diff_key.php';
}
?>
up
0
vlad_mustafin at ukr dot net
7 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
0
denis noessler
8 years ago
if (!function_exists('array_diff_key'))
{
    /**
    * Computes the difference of arrays using keys for comparison
    *
    * @param    array    $valuesBase            Base elements for comparison, associative
    * @param    array    $valuesComp[,..]    Comparison elements, associative
    *
    * @param    array                        Elements, not existing in comparison element, associative
    */
    function array_diff_key()
    {
        $argCount   = func_num_args();
        $argValues  = func_get_args();
        $valuesDiff = array();
       
        if ($argCount < 2)
        {
            return false;
        }
       
        foreach ($argValues as $argParam)
        {
            if (!is_array($argParam))
            {
                return false;
            }
        }
       
        foreach ($argValues[0] as $valueKey => $valueData)
        {
            for ($i = 1; $i < $argCount; $i++)
            {
                if (isset($argValues[$i][$valueKey]))
                {
                    continue 2;
                }
            }
           
            $valuesDiff[$valueKey] = $valueData;
        }
       
        return $valuesDiff;
    }
}
up
-1
y-evt at ya dot ru
11 months ago
else one recursive variation.

<?php
$a
= ['one' => 0, 'two' => ['y' => 0, 'x' => ['e' => 0, 'a' => 0]]];
$b = ['one' => 0, 'two' => ['y' => 0, 'x' => ['e' => 0, 'g' => 0]]];

function
array_diff_key_recursive($a1, $a2) {
    if (
is_array($a2)) {
       
$r = array_diff_key($a1, $a2);
    }
    else {
        return
$a1;   
    }
   
    foreach(
$a1 as $k => $v) {
        if (
is_array($v)) {
           
$r[$k] = array_diff_key_recursive($a1[$k], $a2[$k]);
            if (
is_array($r[$k]) && count($r[$k])==0) unset($r[$k]);
        }
    }
    return
$r;
}
?>
up
-1
contact at autonoma dot fr
5 years ago
after kwutzke's comment , here is a PHP4 array_diff_key fonction for those in need

    function PHP4_array_diff_key()
    {
        $arrs = func_get_args();
        $result = array_shift($arrs);
        foreach ($arrs as $array) {
            foreach ($result as $key => $v) {
                if (array_key_exists($key, $array)) {
                    unset($result[$key]);
                }
            }
        }
        return $result;
   }

works for me, enjoy.
up
-1
kwutzke @ somewhere in the net
6 years ago
PHP4 array_diff_key can be copied from the array_intersect_key implementation posted by some anonymous user on 2006-07-17. The only thing you have to do is to delete the '!' in the if and rename the function.
up
-1
eric dot broersma at phil dot uu dot nl
8 years ago
<?php
function array_diff_key()
{
   
$args = func_get_args();
    return
array_flip(call_user_func_array('array_diff',
          
array_map('array_flip',$args)));
}
?>

 
show source | credits | sitemap | contact | advertising | mirror sites