Example 1 — Keep Matching Keys
Compare two arrays and keep only the keys that appear in both.
<?php
$a = ["red" => 1, "green" => 2, "blue" => 3];
$b = ["red" => 10, "blue" => 30, "pink" => 40];
$result = array_intersect_key($a, $b);
echo json_encode($result), PHP_EOL;
echo count($result), PHP_EOL; How It Works
- Create two arrays. They share the keys
redandblue. - Call array_intersect_key(). PHP checks each key of
$aagainst$b. - Read the result. The values
1and3come from$a, not from$b. - Count the items. Two keys matched, so
count()prints2.

