PHP array_intersect_key()Functions
Example
Compare thekey namesof two arrays, and return the intersection:
<?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);
?>
$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);
?>
Run Example »
Definition and Usage
The array_intersect_key() function is used to compare thekey namesof two (or more) arrays, and returns the intersection.
This function compares the key names of two (or more) arrays, and returns an intersection array that includes all key names that are present in the compared array (array1) and also in any other parameter array (array2orarray3etc.).
Syntax
array_intersect_key(array1,array2,array3...)
| Parameter | Description |
|---|---|
| array1 | Required. The first array to compare with other arrays. |
| array2 | Required. The array to compare with the first array. |
| array3,... | Optional. Other arrays to compare with the first array. |
Technical Details
| Return value: | Returns an intersection array that includes all key names that are present in the compared array (array1) and also in any other parameter array (array2orarray3etc.). |
|---|---|
| PHP Version: | 5.1.0+ |
More Examples
Example 1
Compare thekey namesof two numeric arrays, and return the intersection:
<?php
$a1=array("red","green","blue","yellow");
$a2=array("red","green","blue");
$result=array_intersect_key($a1,$a2);
print_r($result);
?>
$a1=array("red","green","blue","yellow");
$a2=array("red","green","blue");
$result=array_intersect_key($a1,$a2);
print_r($result);
?>
Run Example »
Example 2
Compare thekey namesof three arrays, and return the intersection:
<?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);
?>
$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);
?>
Run Example »
Complete PHP Array Reference Other Extensions