array_intersect_key() keeps entries from the first array whose keys exist in all comparison arrays. Values are not used to determine a match.
$first = ['name' => 'Ravi', 'city' => 'Hyderabad'];
$second = ['name' => 'Mina', 'age' => 24];
$result = array_intersect_key($first, $second);
print_r($result);The value returned is always taken from the first array.
$new_array = array_intersect_key ($array1, $array2,....);
$array1 : Required , the input array which will be checked. $first=array('One' =>1,'Two'=>2,'Three'=>3,'Four'=>'Fourth');
$second=array('One'=>1,'Two'=>2,'Third'=>3);
$result1=array_intersect_key($first,$second);
foreach ($result1 as $key => $val) {
echo "$key -> $val <br>";
}
Output is here.
One -> 1
Two -> 2
Keys of the first index are retained. ( no re-indexing done here) . The third element is not included as the key is different in both arrays.
$first=array('One' =>1,'Two'=>2,'Three'=>3,'Four'=>'Fourth');
$second=array('One'=>1,'Two'=>2,'Third'=>3);
$third=array('One'=>1);
$result1=array_intersect_key($first,$second,$third);
foreach ($result1 as $key => $val) {
echo "$key -> $val <br>";
}
Output is here.
One -> 1
$array1 = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
$array2 = ['a' => 'avocado', 'b' => 'blueberry'];
$result = array_intersect_key($array1, $array2);
print_r($result);
// Output: Array ( [a] => apple [b] => banana )
$array1 = ['name' => 'John', 'age' => 25, 'gender' => 'male', 'country' => 'USA'];
$keys_to_keep = ['name' => '', 'age' => ''];
$result = array_intersect_key($array1, $keys_to_keep);
print_r($result);
// Output: Array ( [name] => John [age] => 25 )
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.