The array_intersect_assoc Function
The array_intersect_assoc
function returns an array containing all the elements of the first array that exist in all other passed arrays, while both keys and values are compared. The first parameter is the main array, the subsequent parameters are arrays for comparison.
Syntax
array_intersect_assoc(array1, array2, ...): array;
Example
Let's find the intersection of two arrays with key check:
<?php
$arr1 = ['a' => 1, 'b' => 2, 'c' => 3];
$arr2 = ['a' => 1, 'c' => 4, 'd' => 5];
$res = array_intersect_assoc($arr1, $arr2);
print_r($res);
?>
Code execution result:
['a' => 1]
Example
Comparison of three arrays with different keys and values:
<?php
$arr1 = [1, 2, 3, 4];
$arr2 = [1, 3, 4, 5];
$arr3 = [1, 2, 4, 6];
$res = array_intersect_assoc($arr1, $arr2, $arr3);
print_r($res);
?>
Code execution result:
[0 => 1]
Example
When there are no matches by keys and values:
<?php
$arr1 = ['a' => 1, 'b' => 2];
$arr2 = ['c' => 1, 'd' => 2];
$res = array_intersect_assoc($arr1, $arr2);
print_r($res);
?>
Code execution result:
[]
See Also
-
the
array_intersect
function,
which computes the intersection of arrays without key check -
the
array_diff_assoc
function,
which computes the difference of arrays with key check