PHP Reference ยท Array Functions
PHP array_intersect_key() function
Reference for PHP array_intersect_key(): keep only entries whose keys exist in other arrays, whitelist fields, and learn how it differs from array_intersect().
array_intersect_key() returns the entries of the first array whose keys are present in every other array. The values of the other arrays are never looked at, so they can be anything: 1, true, or null.
Its best-known use is a whitelist: combine it with array_flip() to keep only the fields you expect from untrusted input.
<?php $row = ["id" => 7, "name" => "Ann", "secret" => "x"]; print_r(array_intersect_key($row, ["id" => 0, "name" => 0])); // ["id" => 7, "name" => "Ann"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_intersect_key(array $array, array ...$arrays): array
| Name | Description |
|---|---|
$array |
The array to filter. Its keys, values and order are kept. |
...$arrays |
Arrays whose keys decide what stays. A key must exist in all of them. |
Return value: an array with the entries of $array that have a matching key in every other array.
Usage notes
- Only keys matter. A key whose value is
nullin the other array still counts as present. This differs fromisset(). - The first array is the source. Values in the result always come from it, even when the other arrays have different values for the same key.
- Whitelist pattern:
array_intersect_key($data, array_flip($allowedNames)). The reverse pattern, removing a blacklist, usesarray_diff_key(). - Integer-like string keys such as
"5"are normalized to the integer5in every array, so they match. - Related variants:
array_intersect_assoc()also compares values,array_intersect_ukey()compares keys with your callback. - Fast: keys are hash lookups, so this is usually much quicker than
array_intersect()on values.