Skip to content
PHP Logo

What is the difference between array_intersect_key and array_intersect in PHP?

The main difference between array_intersect_key and array_intersect in PHP is the way they compare arrays. array_intersect_key compares the keys of two arrays, while array_intersect compares the values of two arrays. If you want to find the intersection of two arrays based on their keys, you should use array_intersect_key. If you want to find the intersection of two arrays based on their values, you should use array_intersect.

php
// Using array_intersect_key to find the intersection of two arrays based on keys
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['a' => 4, 'b' => 2, 'd' => 5];

$intersect = array_intersect_key($array1, $array2);

print_r($intersect);