array_intersect_key
Returns the elements of the first array whose keys are present in the others.
Syntax
array_intersect_key(array $array, array ...$arrays): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array to take elements from. |
| ...$arrays | array | The arrays whose keys are compared against. |
Return value
arrayThe elements with shared keys.
Examples
Keeping only the allowed form fields:
<?php
$input = ['name' => 'Anna', 'email' => 'a@example.com', 'is_admin' => 1];
$allowed = array_flip(['name', 'email']);
echo json_encode(array_intersect_key($input, $allowed));Output:
{"name":"Anna","email":"a@example.com"}Notes
This guards against extra fields in a request: a visitor cannot slip in a field that is not on the list.
See also
- array_intersect — Returns the values present in every array.
- array_diff_key — Returns the elements of the first array whose keys are absent from the others.
In the tutorial
- Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.