array_intersect_key

(PHP 5 >= 5.1.0RC1)

array_intersect_key -- Вычислить пересечение массивов, сравнивая ключи

Описание

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

array_intersect_key() возвращает массив, содержащий значения array1, имеющие ключи, содержащиеся во всех последующих параметрах..

Пример 1. Пример использования array_intersect_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_intersect_key($array1, $array2));
?>

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

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
})

В нашем примере только ключи 'blue' и 'green' содержатся в обоих массивах и поэтому возвращаются. Также обратите внимание, что значения, соответствующие ключам 'blue' и 'green' различны в исходных массивах. Совпадение происходит, так как сравниваются только ключи. Возвращаемые значения берутся из array1.

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

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



array_intersect_key
17-Jul-2006 05:31
Here it is a more obvious way to implement the function:

if (!function_exists('array_intersect_key')) {
   function array_intersect_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;
   }
}
Anton Backer
30-Mar-2006 11:49
Jesse: no, array_intersect_key does not accomplish the same thing as what you posted:

array_flip (array_intersect (array_flip ($a), array_flip ($b)))

because when the array is flipped, values become keys. having duplicate values is not a problem, but having duplicate keys is. array_flip resolves it by keeping only one of the duplicates and discarding the rest. by the time you start intersecting, you've already lost information.
dak
23-Jan-2006 08:31
A more efficient (and, I think, simpler) compatibility implementation:

<?php
if (!function_exists('array_intersect_key'))
{
   function
array_intersect_key ($isec, $arr2)
   {
      
$argc = func_num_args();
        
       for (
$i = 1; !empty($isec) && $i < $argc; $i++)
       {
            
$arr = func_get_arg($i);
            
             foreach (
$isec as $k =>& $v)
                 if (!isset(
$arr[$k]))
                     unset(
$isec[$k]);
       }
      
       return
$isec;
   }
}
?>
Silvio Ginter
23-Sep-2005 05:17
Based on the code posted by gaylord dot aulke at 100days.de
i wrote this one. This should implement this function in all versions equal or greater than PHP 4.0

function array_intersect_key($arr1, $arr2) {
   $res = array();
   foreach($arr1 as $key=>$value) {
       $push = true;
       for ($i = 1; $i < func_num_args(); $i++) {
           $actArray = func_get_arg($i);
           if (gettype($actArray) != 'array') return false;
           if (!array_key_exists($key, $actArray)) $push = false;
       }
       if ($push) $res[$key] = $arr1[$key];
   }
   return $res;
}
gaylord dot aulke at 100days.de
04-Jul-2005 04:04
I tried to use this function with PHP 5.0.4 under windows but the function does not seem to be implemented.
(Fatal error: Call to undefined function array_intersect_key())

This works as a workaround for 2 arrays at least:

function array_intersect_key($arr1, $arr2) {
  $res = array();
  foreach($arr1 as $key=>$value) {
   if(array_key_exists($key, $arr2)) $res[$key] = $arr1[$key];
  }
  return $res;
}
aidan at php dot net
29-May-2005 08:51
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat

<array_intersect_assocarray_intersect_uassoc>
 Last updated: Tue, 15 Nov 2005