Search code examples
phparraysmappingfiltering

Filter array by its key using the values of another array and order results by second array


Here is data

$array = array(
    'random' => 1,
    'pewpew' => 2,
    'temp' => 5,
    'xoxo' => 3,
    'qweqweqe' => 4,
);

$fields = array('random', 'xoxo', 'temp');

I need to get in result:

$result = array(
    'random' => 1,
    'xoxo' => 3,
    'temp' => 5,
);

I mean keys presence/order from $fields apply to $array.

The question is: Can I perform this transformation using only array_ functions? (I don't wanna use iteations) If yes: can you link me function that I need?

(sorry for spelling mistakes)

upd.

PHP 5.2


Solution

  • This code preserves order and works in PHP 5.2 as required

    One line:

    $result = array_merge( array_flip($fields),
                           array_intersect_key(
                                              $array,
                                              array_flip( $fields )
                                              )
                           );
    

    For performance:

    $flip = array_flip($fields);
    $result = array_merge( $flip
                           array_intersect_key(
                                              $array,
                                              $flip
                                              )
                           );