HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Filtering array by list of keys in PHP 5.5

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayphpkeyslistfiltering

Problem

I have an associative array with data (let's say language codes and descriptions) and a second array with allowed keys (lang codes). I want to filter the data array by these allowed keys.

The problem is I'm bound to PHP 5.5 and I can't use ARRAY_FILTER_USE_KEY flag.

I came up with the following solution:

$langs = [
 'en' => "English",
 'de' => "German",
 'fr' => "French",
 'ru' => "Russian",
];

$allowed_langs = ['en','de'];

var_export( 
array_map( function($lang) use($langs) {return $langs[$lang];} , array_combine($allowed_langs, $allowed_langs))
);

/* Output as expected:
array (
  'en' => 'English',
  'de' => 'German',
)
*/


I wonder is there a more elegant and shorter solution to this task?

Solution

I always believe that you should use built in functions wherever possible, as opposed to recreating PHP functionality with loops etc. The main reasons for saying this are that:

  • We should trust that PHP functions achieve their desired result in an efficient manner, and:



  • If they are improved in future versions your code doesn't need to change, but just gets better.



That being said, why not something like this:

$matches = array_intersect_key($langs, array_flip($allowed_langs));
var_export($matches);

Code Snippets

$matches = array_intersect_key($langs, array_flip($allowed_langs));
var_export($matches);

Context

StackExchange Code Review Q#135840, answer score: 7

Revisions (0)

No revisions yet.