I have an array with some values (numeric values):

$arr1 = [1, 3, 8, 12, 23]

and I have another associative array that a key (which matches to a value of $arr1) correspond to a value. This array may contain also keys that don't match with $arr1.

$arr2 = [1 => "foo", 2 => "foo98", 3 => "foo20", 8 => "foo02", 12 => "foo39", 15 => "foo44", 23 => "foo91", 34 => "foo77"]

I want as return the values of $arr2 specifying as key the values of $arr1:

["foo", "foo20", "foo02", "foo39", "foo91"]

If possible, all this, without loops, using just PHP array native functions (so in an elegant way), or at least with the minimum number of loops possible.

2 Answers

3
dWinder On Best Solutions

Minimal loop is simple - 1. as:

foreach($arr1 as $k) {
    $res[] = $arr2[$k];
}

You can do that with array_walk but I think this simple way is more readable.

If you insist you can do with array_filter + array_values + in_array as:

$res = array_values(array_filter($arr2,
    function ($key) use ($arr1) { return in_array($key, $arr1);},
    ARRAY_FILTER_USE_KEY
));

You can see this for more about filtering keys

1
Nigel Ren On

To do it purely with array functions, you could do it as...

print_r(array_intersect_key($arr2, array_flip($arr1) ));

So array_flip() turns the items you want form the array into the keys for $arr1 and then uses array_intersect_key() to match the keys with the main array and this newly created array.

Gives...

Array
(
    [1] => foo
    [3] => foo20
    [8] => foo02
    [12] => foo39
    [23] => foo91
)

If you don't want the keys - add array_values() around the rest of the calls...

print_r(array_values(array_intersect_key($arr2, array_flip($arr1) )));

to get

Array
(
    [0] => foo
    [1] => foo20
    [2] => foo02
    [3] => foo39
    [4] => foo91
)

Although as pointed out - sometimes a simple foreach() is just as good and sometimes better.