187 of 410 menu

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

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

Example

Compare two arrays by keys:

<?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:

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

Example

Compare three arrays by keys:

<?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:

[1 => 'a']

Example

Comparing arrays with different key types:

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

Code execution result:

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

See Also

byenru