Array Functions

PHP array_intersect_key() Function

Topic: PHP Array ReferencePrev|Next

Description

The array_intersect_key() function compares the keys of two or more arrays and returns the matches. The keys values are not considered in the comparison, only the keys are checked.

The following table summarizes the technical details of this function.

Return Value: Returns an array containing all the elements from array1 whose keys are present in all of the other arrays.
Version: PHP 5.1.0+

Syntax

The basic syntax of the array_intersect_key() function is given with:

array_intersect_key(array1, array2, ...);

The following example shows the array_intersect_key() function in action.

<?php
// Sample arrays
$array1 = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "dog");
$array2 = array("a"=>"apricot", "b"=>"banana");

// Computing the intersection
$result = array_intersect_key($array1, $array2);
print_r($result);
?>

Parameters

The array_intersect_key() function accepts the following parameters.

Parameter Description
array1 Required. Specifies the array to compare from.
array2 Required. Specifies an array to compare keys against.
... Optional. Specifies more arrays to compare keys against.

More Examples

Here're some more examples showing how array_intersect_key() function actually works:

In the following example this function compares an array against two other arrays.

<?php
// Sample arrays
$array1 = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "dog");
$array2 = array("a"=>"apricot", "b"=>"banana");
$array3 = array("a"=>"alligator", "d"=>"dog");

// Computing the intersection
$result = array_intersect_key($array1, $array2, $array3);
print_r($result);
?>

The two keys from the key=>value pairs are considered equal if their string representation are same, i.e., (string) $key1 === (string) $key2. Let's try out the following example:

<?php
// Sample arrays
$array1 = array(1, 2, 5, 7, 10);
$array2 = array(0, "1"=>3, "x"=>8, "4"=>13);

// Computing the intersection
$result = array_intersect_key($array1, $array2);
print_r($result);
?>
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties