PHP sorting array_intersect_key() results by second array

Perhaps array_replace is the missing piece to your puzzle:

public function getAsList($list = array())
{
  $klist = array_flip($list);
  return array_values(array_intersect_key(array_replace($klist, $this->hidden), $klist));
}

Example (Demo):

$hidden = [
  'apples' => 19,
  'eggs' => 7,
  'grapes' => 144,
  'mushrooms' => 3,
  'oranges' => 16
];

$list = ['grapes', 'apples', 'eggs', 'oranges'];

$klist = array_flip($list);
print_r(array_values(array_intersect_key(array_replace($klist, $hidden), $klist)));

/*
Array
(
    [0] => 144
    [1] => 19
    [2] => 7
    [3] => 16
)
*/

This is one of those cases when functional programming pales in comparison to a language construct in terms of readability, maintanability, and efficiency.

I have a bias toward functional programming, but in this case it just doesn't pay.

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);

Output:

array (
  0 => 144,
  1 => 19,
  2 => 7,
  3 => 16,
)

If you insist on using functional programming, then it would be most efficient to perform the required operations in this order:

  • filter the array
  • order the keys of the filtered array
  • reindex the ordered, filtered array

Here is how:

Code: (Demo)

$flippedList = array_flip($list);
var_export(array_values(array_replace($flippedList, array_intersect_key($hidden, $flippedList))));

(same output as previous snippet)

Logically, it doesn't make sense to order an array that has excess elements in it. Lighten the load, first.

Tags:

Php

Sorting