This is one of those cases when functional programming pales in comparison with the language design in terms of readability, ease of maintenance and efficiency.
I have a penchant for functional programming, but in this case it just doesn't pay off.
Code: ( Demo )
$hidden = [ 'apples' => 19, 'eggs' => 7, 'grapes' => 144, 'mushrooms' => 3, 'oranges' => 16 ]; $list = ['grapes', 'apples', 'eggs', 'oranges']; foreach ($list as $item) { if (isset($hidden[$item])) { $result[] = $hidden[$item]; } } var_export($result);
Exit:
array ( 0 => 144, 1 => 19, 2 => 7, 3 => 16, )
If you insist on using functional programming, it would be most efficient to perform the necessary operations in the following order:
- filter array
- arrange the keys of the filtered array
- reindex ordered, filtered array
Here's how:
Code: ( Demo )
$flippedList = array_flip($list); var_export(array_values(array_replace($flippedList, array_intersect_key($hidden, $flippedList))));
(the same conclusion as in the previous fragment)
It is logical that it makes no sense to order an array in which there are extra elements. Lighten the load first.
mickmackusa
source share