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

search for in the

array_intersect_uassoc> <array_intersect_assoc
[edit] Last updated: Fri, 18 May 2012

view this page in

array_intersect_key

(PHP 5 >= 5.1.0)

array_intersect_keyErmittelt die Schnittmenge von Arrays, indem es die Schlüssel vergleicht

Beschreibung

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

array_intersect_key() gibt ein Array zurück, welches alle Werte von array1 enthält, die Schlüssel besitzen, die in allen anderen Argumenten enthalten sind.

Parameter-Liste

array1

Das Array mit den Hauptschlüsseln, auf die geprüft werden soll.

array2

Ein Array, gegen welches die Schlüssel geprüft werden.

array

Eine variable Liste zu vergleichender Arrays.

Rückgabewerte

Gibt ein assoziatives Array zurück, welches alle Einträge von array1 enthält, deren Schlüssel in allen weiteren Arrays vorhanden sind.

Beispiele

Beispiel #1 array_intersect_key()-Beispiel

<?php
$array1 
= array('blau' => 1'rot'  => 2'grün' => 3'violett' => 4);
$array2 = array('grün' => 5'blau' => 6'gelb' => 7'türkis'  => 8);

var_dump(array_intersect_key($array1$array2));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

array(2) {
  ["blau"]=>
  int(1)
  ["grün"]=>
  int(3)
})

In unserem Beispiel sehen Sie, dass nur die Schlüssel 'blau' und 'grün' in beiden Arrays vorhanden sind und daher zurückgegeben werden. Beachten Sie auch, dass 'blau' und 'grün' in beiden Arrays unterschiedliche Werte besitzen. Eine Übereinstimmung wird dennoch festgestellt, da nur die Schlüssel geprüft werden. Die zurückgegebenen Werte sind diejenigen aus array1.

Die beiden Schlüssel des Schlüssel => Wert-Paares werden als gleich erachtet, genau dann wenn (string) $key1 === (string) $key2 . Anders ausgedrückt findet eine strikte Prüfung statt, in der die String-Repräsentationen gleich sein müssen.

Siehe auch

  • array_diff() - Ermittelt die Unterschiede zwischen Arrays
  • array_udiff() - Ermittelt den Unterschied zwischen Arrays mittels einer Callbackfunktion für den Datenvergleich
  • array_diff_assoc() - Berechnet den Unterschied zwischen Arrays mit zusätzlicher Indexprüfung
  • array_diff_uassoc() - Berechnet den Unterschied von Arrays mit zusätzlicher Indexprüfung, welche durch eine benutzerdefinierte Funktion vorgenommen wird
  • array_udiff_assoc() - Ermittelt den Unterschied zwischen Arrays mit zusätzlicher Indexprüfung, vergleicht mittels einer Callbackfunktion
  • array_udiff_uassoc() - Ermittelt den Unterschied zwischen Arrays mit zusätzlicher Indexprüfung, vergleicht Daten und Indizes mittels einer Callbackfunktion
  • array_diff_key() - Berechnet den Unterschied zwischen Arrays, indem es die Schlüssel vergleicht
  • array_diff_ukey() - Berechnet den Unterschied zwischen Arrays mittels einer Callbackfunktion für den Vergleich der Schlüssel
  • array_intersect() - Ermittelt die Schnittmenge von Arrays
  • array_intersect_assoc() - Ermittelt die Schnittmenge von Arrays mit Indexprüfung
  • array_intersect_uassoc() - Ermittelt die Schnittmenge von Arrays mit Indexprüfung; vergleicht Indizes mit einer Callbackfunktion
  • array_intersect_ukey() - Ermittelt die Schnittmenge zweier Arrays mittels eines durch eine Callbackfunktion durchgeführten Schlüsselvergleiches



array_intersect_uassoc> <array_intersect_assoc
[edit] Last updated: Fri, 18 May 2012
 
add a note add a note User Contributed Notes array_intersect_key
pgl at yoyo dot org 18-Jul-2011 08:01
Note that the order of the keys in the returned array is the same as the order of the keys in the source array. eg:

<?php
$array
= array(
   
'two'   => 'a',
   
'three' => 'b',
   
'one'   => 'c',
    );

$keyswant = array(
   
'one'       => '',
   
'three'     => '',
    );

print_r(array_intersect_key($array, $keyswant));

?>

Shows:

Array
(
    [three] => b
    [one] => c
)
chrisbloom7 at gmail dot com 11-Nov-2009 10:23
Regarding php at keithtylerdotcom solution to emulate

<?php
$z
= someFuncReturningAnArray()['some_key'];
?>

His recommended solution will still return an array. To get the value of a single key in an array returned by a function, simply add implode() to the recipe:

<?php
function someFuncReturningAnArray() {
  return array(
   
'a' => 'b',
   
'c' => 'd',
   
'e' => 'f',
   
'g' => 'h',
   
'i' => 'j'
 
);
}

//traditional way
$temp = someFuncReturningAnArray();
$b = $temp['a'];
echo
print_r($b, 1) . "\n----------\n";

//keithtylerdotcom one-line method
$b = array_intersect_key(someFuncReturningAnArray(), array('a'=>''));
echo
print_r($b, 1) . "\n----------\n";

//better one line method
$b = implode('', array_intersect_key(someFuncReturningAnArray(), array('a'=>'')));
echo
print_r($b, 1) . "\n----------\n";
?>
markus dot kappe at dix dot at 24-Sep-2009 04:43
<?php
   
/**
     * calculates intersection of two arrays like array_intersect_key but recursive
     *
     * @param  array/mixed  master array
     * @param  array        array that has the keys which should be kept in the master array
     * @return array/mixed  cleand master array
     */
   
function myIntersect($master, $mask) {
        if (!
is_array($master)) { return $master; }
        foreach (
$master as $k=>$v) {
            if (!isset(
$mask[$k])) { unset ($master[$k]); continue; } // remove value from $master if the key is not present in $mask
           
if (is_array($mask[$k])) { $master[$k] = $this->myIntersect($master[$k], $mask[$k]); } // recurse when mask is an array
            // else simply keep value
       
}
        return
$master;
    }
?>
pdemaziere at gmail dot com 23-Feb-2009 07:52
Just a simple script if you want to use one array, which contains only zeros and ones, as mask for another one (both arrays must have the same size of course). $outcome is an array that contains only those values from $source where $mask is equal to 1.

<?php
$outcome
= array_values(array_intersect_key( array_values($source), array_filter(array_values($mask)) ));
?>

PS: the array_values() function is necessary to ensure that both arrays have the same numbering/keys, otherwise your masking does not behave as you expect.

Enjoy!
CBWhiz at gmail dot com 04-Jan-2008 02:04
I have found the following helpful:
<?PHP
function array_merge_default($default, $data) {
       
$intersect = array_intersect_key($data, $default); //Get data for which a default exists
       
$diff = array_diff_key($default, $data); //Get defaults which are not present in data
       
return $diff + $intersect; //Arrays have different keys, return the union of the two
}
?>
It's use is like both of the functions it uses, but keeps defaults and _only_ defaults. It's designed for key arrays, and i'm not sure how it will work on numeric indexed arrays.

Example:
<?PHP
$default
= array(
 
"one" => 1,
 
"two" => 2
);
$untrusted = array(
 
"one" => 42,
 
"three" => 3
);
var_dump(array_merge_default($default, $untrusted));

array(
2) {
  [
"two"]=>
 
int(2)
  [
"one"]=>
 
int(42)
}

?>
Rod Byrnes 05-May-2007 09:10
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;
    }
  }
}
?>
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

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