Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : array_intersect_key

array_intersect_key

Computes the intersection of arrays using keys for comparison (PHP 5 >= 5.1.0)
array array_intersect_key ( array array1, array array2 [, array ...] )

array_intersect_key() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.

Parameters

array1

The array with master keys to check.

array2

An array to compare keys against.

array

A variable list of arrays to compare.

Return Values

Returns an associative array containing all the values of array1 which have matching keys that are present in all arguments.

Examples

Example 250. array_intersect_key() example

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

The above example will output:

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


In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.

Code Examples / Notes » array_intersect_key

aidan

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


anton backer

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.


gaylord dot aulke

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;
}


17-jul-2006 01: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;
  }
}


rod byrnes

Here is a faster version than those shown below, with optimisation for the case when only two arrays are passed. In my tests with a 10000 item first array and a 5000 item second array (run 20 times) this function ran in 1.89 seconds compared with 2.66 for the version posted by dak. For a three array case, same as above but with the third array containing 3333 values, the timing is 3.25 for this version compared with 3.7 for dak's version.
<?php
if (!function_exists('array_intersect_key'))
{
 function array_intersect_key($isec, $keys)
 {
   $argc = func_num_args();
   if ($argc > 2)
   {
     for ($i = 1; !empty($isec) && $i < $argc; $i++)
     {
       $arr = func_get_arg($i);
       foreach (array_keys($isec) as $key)
       {
         if (!isset($arr[$key]))
         {
           unset($isec[$key]);
         }
       }
     }
     return $isec;
   }
   else
   {
     $res = array();
     foreach (array_keys($isec) as $key)
     {
       if (isset($keys[$key]))
       {
         $res[$key] = $isec[$key];
       }
     }
     return $res;
   }
 }
}
?>


silvio ginter

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;
}


dak

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


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker