Search code examples
phparrayskeyarray-intersect

get array elements which have key in second array in php


I need only array elements which have their keys in values of second array, with the fastest script.

$array_1 = array(
    'ana' => 'are',
    'du'  => 34,
    'bopq'=> "Ana are mere mereu",
    13    => "OK"
);

$array_2 = array('du', 13);

$expected_array = array(
    'du' => 34,
    13   => "OK"
);

There is faster solution than:

$expected_array = array_intersect($array_1, array_combine($array_2, $array_2);

?


Solution

  • Array_intersect_key is what you are looking for.

    $array_1 = array(
        'ana' => 'are',
        'du'  => 34,
        'bopq'=> "Ana are mere mereu",
        13    => "OK"
    );
    
    $array_2 = array('du', 13);
    
    $result = array_intersect_key($array_1, array_flip($array_2));
    

    https://3v4l.org/P6jkq