PHP array_intersect_key() function

PHP array_intersect_assoc() function
PHP array_intersect_uassoc() function

The array_intersect_key function simply compares the first array with the other array or arrays based on keys. It returns an associative array that only contains the result against matching keys.

If the key in the first array is found in the rest of the arrays, it is included in the resultant array.

What is the syntax of array_interse functionct_key in PHP?

array_intersect_key(array1, array2, array3, ...)
ParametersDetails
array1Array to make comparison from – Required
array2Array to compare with – Required
array3,…Further arrays to compare with – Required
array_intersect_key function in PHP

Examples of array_intersect_key function

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"red","c"=>"blue","d"=>"pink");

$result=array_intersect_key($a1,$a2);
print_r($result);
?>

In the above example, the array_intersect function compares only the keys of two arrays and returns the matches.

<?php
$a1=array("red","green","blue","yellow");
$a2=array("red","green","blue");

$result=array_intersect_key($a1,$a2);
print_r($result);
?>

In the above example, we use the array_intersect_key function with an indexed array. The elements of each indexed array are now treated as the keys. Therefore, the function compares them with the second array and returns the matches.

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("c"=>"yellow","d"=>"black","e"=>"brown");
$a3=array("f"=>"green","c"=>"purple","g"=>"red");

$result=array_intersect_key($a1,$a2,$a3);
print_r($result);
?>

In the above example, the array_intersect function compares only the keys of three arrays and returns the matches.

PHP array_intersect_assoc() function
PHP array_intersect_uassoc() function

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top