Search code examples
phparrayssearchintersect

Intersect associative array from another array in php


I have two array that is

$a = array( 
    array(
        'id' => 1,
        'name' => "Facebook" 
    ),
    array(
        'id' => 2,
        'name' => "Twitter" 
    ),
    array(
        'id' => 3,
        'name' => "Google" 
    ),
    array(
        'id' => 4,
        'name' => "Linkdin" 
    ),
    array(
        'id' => 5,
        'name' => "Github" 
    ),
);

And another is,

$b = array(1, 3, 5);

According to the $b array value, $a associative array id will be selected as result. intersect two array So the result will be,

$result = $a = array( 
    array(
        'id' => 1,
        'name' => "Facebook" 
    ),
    array(
        'id' => 3,
        'name' => "Google" 
    ),
    array(
        'id' => 5,
        'name' => "Github" 
    ),
);

Solution

  • Simple oneliner (more readable with 4 lines though):

    $result = array_filter(
        $a, 
        function($v) use ($b) { return in_array($v['id'], $b); }
    );