PHP array_intersect_key() Function

Quick summary: The PHP array_intersect_key() function returns all elements from the first array whose keys are present in all other arrays.

PHP array_intersect_key() Syntax

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

PHP array_intersect_key() Basic examples

$a = ['a'=>1,'b'=>2,'c'=>3];
$b = ['a'=>9,'c'=>8];
print_r(array_intersect_key($a, $b));
PHP
Output:
Array ( [a] => 1 [c] => 3 )

Returns elements whose keys exist in both arrays.

PHP array_intersect_key() Real-world usage

$input = ['name'=>'John','email'=>'john@example.com','role'=>'admin'];
$allowed = ['name'=>true,'email'=>true];
print_r(array_intersect_key($input, $allowed));
PHP
Output:
Array ( [name] => John [email] => john@example.com )

Whitelist filtering of user input.

PHP array_intersect_key() Edge cases

$a = ['1'=>'x'];
$b = [1=>'y'];
print_r(array_intersect_key($a, $b));
PHP
Output:
Array ( [1] => x )

String and integer keys may be treated as identical.

PHP array_intersect_key() Common mistakes

Expecting value comparison

array_intersect_key() compares only keys.

Incorrect
array_intersect_key(['a'=>1], ['a'=>2]);
Correct
array_intersect_assoc(['a'=>1], ['a'=>2]);

Use array_intersect_assoc() if values must also match.

PHP array_intersect_key() Frequently Asked Questions

What does array_intersect_key() do?

Computes intersection using keys only.

Use case?

Filtering by keys.

Ignores values?

Yes.

Return type?

Array.

Common mistake?

Expecting value comparison.

Performance?

Fast.

Safe?

Yes.

Alternative?

array_diff_key().

Handles nested arrays?

No.

Case sensitive?

Yes.

Best practice?

Normalize keys.

Used in configs?

Yes.

PHP array_intersect_key() Related PHP Functions