The array_intersect_key Function

The array_intersect_key function takes several arrays and returns a new array, containing elements from the first array whose keys are present in all other arrays. Comparison is performed only by keys, values are not considered.

Syntax

phparray_intersect_key(array1, array2, array3, ...);

Example

Compare two arrays by keys:

php<?php
  $arr1 = ['a' => 1, 'b' => 2, 'c' => 3];
  $arr2 = ['a' => 4, 'c' => 5, 'd' => 6];
  
  $res = array_intersect_key($arr1, $arr2);
  print_r($res);
?>

Code execution result:

php['a' => 1, 'c' => 3]

Example

Compare three arrays by keys:

php<?php
  $arr1 = [1 => 'a', 2 => 'b', 3 => 'c'];
  $arr2 = [1 => 'd', 3 => 'e'];
  $arr3 = [1 => 'f', 4 => 'g'];
  
  $res = array_intersect_key($arr1, $arr2, $arr3);
  print_r($res);
?>

Code execution result:

php[1 => 'a']

Example

Comparing arrays with different key types:

php<?php
  $arr1 = ['1' => 'a', 2 => 'b'];
  $arr2 = [1 => 'c', '2' => 'd'];
  
  $res = array_intersect_key($arr1, $arr2);
  print_r($res);
?>

Code execution result:

php['1' => 'a', 2 => 'b']

See Also