PHP 8.3.21 Released!

array_intersect_key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

array_intersect_keyCalcula la intersección de dos arrays utilizando las claves para la comparación

Descripción

array_intersect_key(array $array, array ...$arrays): array

array_intersect_key() devuelve un array que contiene todas las entradas del array array que contienen claves presentes en todos los arrays pasados como argumentos.

Parámetros

array

El array que contiene las claves maestras a verificar.

arrays

Arrays a comparar.

Valores devueltos

Devuelve un array asociativo que contiene todas las entradas del array array cuyas claves están presentes en todos los argumentos.

Historial de cambios

Versión Descripción
8.0.0 Esta función ahora puede ser llamada con un solo parámetro. Anteriormente, se requerían al menos dos parámetros.

Ejemplos

Ejemplo #1 Ejemplo con array_intersect_key()

<?php
$array1
= array('azul' => 1, 'rojo' => 2, 'verde' => 3, 'violeta' => 4);
$array2 = array('verde' => 5, 'azul' => 6, 'amarillo' => 7, 'cian' => 8);

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

El resultado del ejemplo sería:

array(2) {
  ["azul"]=>
  int(1)
  ["verde"]=>
  int(3)
}

En este ejemplo, se puede ver que solo las claves 'azul' y 'verde' están presentes en ambos arrays y por lo tanto, son devueltas. Note también que los valores para las claves 'azul' y 'verde' difieren entre los dos arrays. No obstante, aún corresponden porque solo las claves son verificadas. Los valores devueltos son los del array array1.

Las dos claves desde los pares clave => valor son consideradas iguales solo si (string) $clave1 === (string) $clave2 . En otras palabras, se realiza un análisis estricto del tipo, por lo que la representación en forma de string debe ser exactamente la misma.

Ver también

  • array_diff() - Calcula la diferencia entre arrays
  • array_udiff() - Calcula la diferencia entre dos arrays utilizando una función de retrollamada
  • array_diff_assoc() - Calcula la diferencia de dos arrays, teniendo en cuenta las claves
  • array_diff_uassoc() - Calcula la diferencia entre dos arrays asociativos, utilizando una función de retrollamada
  • array_udiff_assoc() - Calcula la diferencia entre arrays con verificación de índices, compara los datos con una función de retrollamada
  • array_udiff_uassoc() - Calcula la diferencia de dos arrays asociativos, compara los datos y los índices con una función de retrollamada
  • array_diff_key() - Calcula la diferencia de dos arrays utilizando las claves para la comparación
  • array_diff_ukey() - Calcula la diferencia entre dos arrays utilizando una función de retrollamada sobre las claves para comparación
  • array_intersect() - Calcula la intersección de arrays
  • array_intersect_assoc() - Calcula la intersección de dos arrays con pruebas sobre los índices
  • array_intersect_uassoc() - Calcula la intersección de dos arrays con pruebas en los índices, compara los índices utilizando una función de retrollamada
  • array_intersect_ukey() - Calcula la intersección de dos arrays utilizando una función de retrollamada sobre las claves para la comparación

add a note

User Contributed Notes 12 notes

up
272
vladas dot dirzys at gmail dot com
12 years ago
Simple key white-list filter:

<?php
$arr
= array('a' => 123, 'b' => 213, 'c' => 321);
$allowed = array('b', 'c');

print_r(array_intersect_key($arr, array_flip($allowed)));
?>

Will return:
Array
(
[b] => 213
[c] => 321
)
up
11
Anonymous
3 years ago
Note that the order of the keys in the returned array is the same as the order of the keys in the source array.

To sort by the second array, then you may do so through array_replace.

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

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

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

?>

Shows:

Array
(
[one] => c
[three] => b
)

Rather than:

Array
(
[three] => b
[one] => c
)
up
22
github.com/xmarcos
10 years ago
[Editor's note: changed array_merge_recursive() to array_replace_recursive() to fix the script]

Here is a better way to merge settings using some defaults as a whitelist.

<?php

$defaults
= [
'id' => 123456,
'client_id' => null,
'client_secret' => null,
'options' => [
'trusted' => false,
'active' => false
]
];

$options = [
'client_id' => 789,
'client_secret' => '5ebe2294ecd0e0f08eab7690d2a6ee69',
'client_password' => '5f4dcc3b5aa765d61d8327deb882cf99', // ignored
'client_name' => 'IGNORED', // ignored
'options' => [
'active' => true
]
];

var_dump(
array_replace_recursive($defaults,
array_intersect_key(
$options, $defaults
)
)
);

?>

Output:

array (size=4)
'id' => int 123456
'client_id' => int 789
'client_secret' => string '5ebe2294ecd0e0f08eab7690d2a6ee69' (length=32)
'options' =>
array (size=2)
'trusted' => boolean false
'active' => boolean true
up
12
pgl at yoyo dot org
13 years ago
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
)
up
3
Reed Silver
10 years ago
If you want an array that has no key value pairs added from the second array:

$new = array_intersect_key($b, $a) + $a;
up
5
CBWhiz at gmail dot com
17 years ago
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)
}

?>
up
3
Anton Backer
19 years ago
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.
up
1
chrisbloom7 at gmail dot com
15 years ago
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";
?>
up
0
Anonymous
14 days ago
May I suggest this array_intersect_key_recursive implementation ?

function array_intersect_key_recursive(array $targetArray, array ...$comparedArrays): array
{
$targetArrayIntersected = array_intersect_key($targetArray, ...$comparedArrays);

foreach (array_keys($targetArrayIntersected) as $key) {
if (true === is_array($targetArray[$key])
// all compared arrays have key with non-empty array as value
&& true === array_reduce(
$comparedArrays,
function (bool $isArrayPreviousSingleComparedArray, array $singleComparedArray) use ($key) {
return (true === $isArrayPreviousSingleComparedArray
&& true === is_array($singleComparedArray[$key])
&& false === empty($singleComparedArray[$key])
);
},
true)
)
{
// repeat recursively
$targetArrayIntersected[$key] = array_intersect_key_recursive(
$targetArray[$key],
...array_map(
function(array $singleComparedArray) use ($key): array {
return $singleComparedArray[$key];
},
$comparedArrays
)
);
}
}
return $targetArrayIntersected;
}
up
0
markus dot kappe at dix dot at
15 years ago
<?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;
}
?>
up
-3
pixelf3hler at visualize-me dot de
11 years ago
in case you came here looking for a function that returns an array containing the values of `all` arrays with intersecting keys:
<?php
function array_merge_on_key($key, $array1, $array2) {
$arrays = array_slice(func_get_args(), 1);
$r = array();
foreach(
$arrays as &$a) {
if(
array_key_exists($key, $a)) {
$r[] = $a[$key];
continue;
}
}
return
$r;
}
// example:
$array1 = array("id" => 12, "name" => "Karl");
$array2 = array("id" => 4, "name" => "Franz");
$array3 = array("id" => 9, "name" => "Helmut");
$array4 = array("id" => 10, "name" => "Kurt");

$result = array_merge_on_key("id", $array1, $array2, $array3, $array4);

echo
implode(",", $result); // => 12,4,9,10
?>
up
-2
pdemaziere at gmail dot com
16 years ago
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!
To Top