Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

array_diff_key

(PHP 5 >= 5.1.0RC1)

array_diff_key -- Вычислить расхождение в массивах, сравнивая ключи

Описание

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

array_diff_key() возвращает массив, содержащий все значения array1, имеющие ключи, не содержащиеся в последующих параметрах. Обратите внимание, что ассоциации сохраняются. Эта функция схожа с array_diff() за исключением того, что сравниваются ключи, а не значения.

Пример 1. Пример использования array_diff_key()

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

Результат выполнения данного примера:

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

Два ключа пар key => value считаются равными только, если (string) $key1 === (string) $key2 . Другими словами, строгая проверка считает, что строковое представление должно быть идентичным.

Замечание: Обратите внимание, что эта функция обрабатывает только одно измерение n-размерного массива. Естественно, вы можете обрабатывать и более глубокие уровни вложенности, например, используя array_diff_key($array1[0], $array2[0]);.

См. также array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_ukey(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc(), array_intersect_key() и array_intersect_ukey().



array_diff_uassoc> <array_diff_assoc
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
array_diff_key
contact at autonoma dot fr
29-Jun-2007 05:01
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.
kwutzke @ somewhere in the net
20-Dec-2006 04:27
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.
2ge at 2ge dot us
07-Mar-2006 11:28
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.
vlad_mustafin at ukr dot net
13-Jan-2006 07:39
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;
    }
}
?>
ampf at egp dot up dot pt
25-Nov-2005 12:55
Well, you could implement in the code something more powerfull:

http://www.php.net/manual/en/function.array-diff.php#31364
ml at iceni dot pl
07-Jun-2005 12:52
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';
}
?>
maxence at pontapreta dot net
27-May-2005 10:38
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$
nicolas at goinf dot com
14-Apr-2005 08:28
Be aware that the last solution doesn't work if for any reason, two values are the same.
eric dot broersma at phil dot uu dot nl
05-Mar-2005 06:58
<?php
function array_diff_key()
{
   
$args = func_get_args();
    return
array_flip(call_user_func_array('array_diff',
          
array_map('array_flip',$args)));
}
?>
denis noessler
23-Nov-2004 04:07
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;
    }
}

array_diff_uassoc> <array_diff_assoc
Last updated: Sat, 27 Jan 2007
 
 
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571