Using array_intersect_key() to Compute Array Intersection by Keys in PHP

This article explains PHP's array_intersect_key() function, detailing its purpose of intersecting arrays based on key names, describing each parameter, return value, and providing a complete example with code and expected output for developers.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using array_intersect_key() to Compute Array Intersection by Keys in PHP

The array_intersect_key() function returns an array containing all the values from the first array whose keys also exist in all other arrays passed as arguments.

Parameters array1: The first array to compare. array2: The array to compare against the first array. array: Additional arrays to compare (optional).

Return Value

An array representing the intersection of the arrays based on matching keys.

Example

<?php
$array1 = array('blue'=>1,'red'=>2,'green'=>3,'purple'=>4);
$array2 = array('green'=>5,'blue'=>6,'yellow'=>7,'cyan'=>8);
var_dump(array_intersect_key($array1,$array2));
?>

Output

array(2) {
  ["blue"]=> int(1)
  ["green"]=> int(3)
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPArrayTutorialarray_intersect_key
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.