PHP 8 reference · Array Functions
PHP array_intersect_key() Function
Return the entries of the first array whose keys exist in all the other arrays. Great for whitelisting fields.
PHP 8 Since 5.1
Syntax
array_intersect_key(array $array, array ...$arrays): array
Parameters
| Parameter | Description |
|---|---|
array |
The input array. |
arrays |
Arrays whose keys are allowed. |
Return value
The entries with matching keys.
Examples
<?php
$input = ["name" => "Ada", "email" => "[email protected]", "is_admin" => true];
$allowed = array_flip(["name", "email"]);
print_r(array_intersect_key($input, $allowed));
Output
Array
(
[name] => Ada
[email] => [email protected]
)<?php
print_r(array_intersect_key(["a" => 1, "b" => 2, "c" => 3], ["c" => 0, "a" => 0]));
Output
Array
(
[a] => 1
[c] => 3
)Version history
| Version | Change |
|---|---|
| PHP 5.1 | Added |
Related
array_diff_key()· Return the entries of the first array whose keys are not in any of the other arrays.array_intersect()· Return the values of the first array that are also present in all the other arrays. Keys come from the first array.array_flip()· Swap keys and values, so each value becomes a key. Values must be strings or integers; duplicates keep the last key.- PHP Array Functions · tutorial
- PHP Arrays · tutorial