'Intersect and Sort an Array by keys based on another Array?

Similar to the question: Sort an Array by keys based on another Array? only I want to drop any keys that arent in common.

Essentially I tried filtering the variables by the keys via array_intersect_key($VARIABLES, array_flip($signature_args)); and then tried to sort it with array_merge(array_flip($signature_args), $filtered)

Shown here:

$VARIABLES = array('3'=>'4', '4'=>'5', '1'=>'2');
$signature_args = array('1', '2', '3');

$filtered = array_intersect_key($VARIABLES, array_flip($signature_args));
var_dump($filtered);

var_dump(array_merge(array_flip($signature_args), $filtered));

produces:

array(2) {
  [3]=>
  string(1) "4"
  [1]=>
  string(1) "2"
}
array(5) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  string(1) "4"
  [4]=>
  string(1) "2"
}

and not the

array(2) {
  [3]=>
  string(1) "4"
  [1]=>
  string(1) "2"
}
array(2) {
  [1]=>
  string(1) "2"
  [3]=>
  string(1) "4"
}

that I expected, why?



Solution 1:[1]

To use the "allowed" array not only to filter the input array but also to order the output, filter both arrays by each other, then replace (or merge) the input array into the allowed array.

Code: (Demo)

$input = ['3' => '4', '4' => '5', '1' => '2'];
$allowed = ['1', '2', '3'];

$flipAllowed = array_flip($allowed);

var_export(
    array_replace(
        array_intersect_key($flipAllowed, $input), // filtered allowed
        array_intersect_key($input, $flipAllowed) // filtered input
    )
);

Output:

array (
  1 => '2',
  3 => '4',
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mickmackusa