find the intersection of two maps in php

To find the intersection of two maps in PHP, you can use the array_intersect_key() function or the array_intersect() function.

The array_intersect() function returns an array containing all the values of the first array that are present in all of the other arrays. To use array_intersect(), you need to convert the maps to arrays using the array() function.

main.php
$map1 = array('a' => 1, 'b' => 2, 'c' => 3);
$map2 = array('b' => 2, 'c' => 4, 'd' => 5);

$result = array_intersect($map1, $map2);
print_r($result); // Output: Array ( [b] => 2 )
180 chars
6 lines

The array_intersect_key() function returns an array containing all the elements of the first array whose keys are present in all of the other arrays.

main.php
$map1 = array('a' => 1, 'b' => 2, 'c' => 3);
$map2 = array('b' => 2, 'c' => 4, 'd' => 5);

$result = array_intersect_key($map1, $map2);
print_r($result); // Output: Array ( [b] => 2 [c] => 3 )
193 chars
6 lines

In the above example, the array_intersect_key() function returns the elements of the first array whose keys are present in the second array.

gistlibby LogSnag