Here's a variation on array_intersect_key() that intersects the first (master) array's keys with the values of other arrays. It can also be used to intersect an array with an arbitrary list of keys (à la compact(), but using a source array instead of current variables):
<?php
function array_intersect_keylist(array $source)
{
$final = $source;
// Loop through all arguments passed
foreach(func_get_args() as $cx=> $keylist) if ($cx)
{
if (!is_array($keylist)) $keylist = Array((string)$keylist);
// Intersect
$final = array_intersect_key($final, array_fill_keys($keylist, ''));
}
return $final;
}
// Example usage
$test = Array('foo' => 'something', 'bar' => 'whatever');
// Returns Array('foo' => 'something')
array_intersect_keylist($test, Array('foo', 'baz') );
// Also returns Array('foo' => 'something')
array_intersect_keylist($test, 'foo', 'baz');
// Equivalent to...
array_intersect_key($test, Array('foo' => '', 'baz' => ''));
?>
array_intersect_key
(PHP 5 >= 5.1.0)
array_intersect_key — Computa a interseção de array comparando pelas chaves
Descrição
array_intersect_key() retorna um array contendo todos os valores de array1 que tem as mesmas chaves presentes em todos os argumentos.
Parâmetros
- array1
-
O array com as chaves a serem verificadas.
- array2
-
Um array para comparar as chaves.
- array
-
Uma variável lista de arrays para comparação.
Valor Retornado
Retorna um array associativo contendo todos os valores de array1 que estão presentes em todos os argumentos.
Exemplos
Exemplo #1 Exemplo da 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));
?>
O exemplo acima irá imprimir:
array(2) {
["blue"]=>
int(1)
["green"]=>
int(3)
}
Em nosso exemplo você pode ver que somente as chaves 'blue' e 'green' estão presentes em ambos array e assim retornado. Também note que os valores das chaves 'blue' e 'green' diferem nos dois arrays. A combinação ocorre porque somente as chaves são verificadas. Os valores retornados são do array1 .
As duas chaves do par key => value são considerados iguais somente se (string) $key1 === (string) $key2 . Em outras palavras um verificação do tipo é executada, então a representação string precisa ser a mesma.
Veja Também
- array_diff() - Analisa as diferenças entre arrays
- array_udiff() - Computa a diferença de arrays usando uma função de callback para comparação dos dados
- array_diff_assoc() - Computa a diferença entre arrays com checagem adicional de índice
- array_diff_uassoc() - Computa a diferença entre arrays com checagem adicional de índice que é feita por uma função de callback fornecida pelo usuário
- array_udiff_assoc() - Computa a diferença entre arrays com checagem adicional de índice, compara dados por uma função de callback
- array_udiff_uassoc() - Computa a diferença entre arrays com checagem adicional de índice, compara dados e índices por uma função de callback
- array_diff_key() - Registra a diferença entre arrays usando chaves para comparação
- array_diff_ukey() - Computa a diferença de arrays usando uma função callback na comparação de chaves
- array_intersect() - Calcula a interseção entre arrays
- array_intersect_assoc() - Computa a interseção de arrays com uma adicional verificação de índice
- array_intersect_uassoc() - Computa a interseção de arrays com checagem de índice adicional, compara índices por uma função de callback
- array_intersect_ukey() - Computa a interseção de arrays usando uma função de callback nas chaves para comparação
array_intersect_key
06-Nov-2009 06:24
03-Nov-2009 01:03
A Q&D way to grab a specific entry from an assoc array returned from a function as a one liner:
Normally when a function returns an array, and you only want part of that array, you have to do:
<?php
$a=func();
$z=$a["desired"];
// ... use $z
?>
However, using an immediate array as the second argument to array_intersect_key allows you to skip this explicit assignment step:
<?php
$z=array_intersect_key(func(),Array("desired"=>""));
// ... use $z
?>
This may be appreciated by those who have been spoiled by the ability of e.g. Python to do:
<?python
z = func()["desired"]
?>
24-Sep-2009 11: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;
}
?>
23-Feb-2009 03: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!
04-Jan-2008 10: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)
}
?>
06-May-2007 04: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;
}
}
}
?>
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;
}
}
31-Mar-2006 07: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.
24-Jan-2006 04: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;
}
}
?>
23-Sep-2005 12: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;
}
04-Jul-2005 11: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;
}
29-May-2005 03: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
