PHP array_intersect_key() function
Example
Compare the key names of 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); ?>
Definition and Usage
The array_intersect_key() function is used to compare the key names of two (or more) arrays and return the intersection.
This function compares the key names of two (or more) arrays and returns an intersection array that includes all the keys in the compared array (array1Also in any other parameter array (array2 Or array3 etc.) of the key names.
Description
The array_intersect_key() function calculates the intersection of arrays using key names.
The array_intersect_key() function returns an array that contains the values of all keys that appear in the compared array and also appear in all other parameter arrays.
Note:Only key names are used for comparison.
Syntax
array_intersect_key(array1,array2,array3...)
Parameters | 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 the key names that are present in the compared array (array1) and also in any other parameter arrays (array2 or array3, etc.). |
PHP Version: | 5.1.0+ |
More Examples
Example 1
Compare the key names of two indexed 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); ?>
Example 2
Compare the key names of 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); ?>