phparraysfilteringassociative-arrayarray-intersect

Filter a flat, associative array by the keys in another flat, associative array


I have two arrays:

$arr1 = array('a' => 10, 'b' => 20);

$arr2 = array('a' => 10, 'b' => 20, 'c' => 30);

How can I use array_filter() to drop elements from $arr2 that don't exist in $arr1? Like "c" in my example.


Solution

  • There is a function specifically made for this purpose: array_intersect():

    array_intersect — Computes the intersection of arrays

    $arr2 = array_intersect($arr1, $arr2);
    

    If you want to compare keys, not the values like array_intersect(), use array_intersect_key():

    array_intersect_key — Computes the intersection of arrays using keys for comparison

    $arr2 = array_intersect_key($arr1, $arr2); 
    

    If you want to compare key=>value pairs, use array_intersect_assoc():

    array_intersect_assoc — Computes the intersection of arrays with additional index check

    $arr2 = array_intersect_assoc($arr1, $arr2);