# Filtering array by list of keys in PHP 5.5

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?

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:

1. We should trust that PHP functions achieve their desired result in an efficient manner, and:
2. 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);

• Yes, indeed! This solution is definitely better than mine. Jul 27 '16 at 12:41
• A similar solution is in the PHP array_filter documentation comments, that uses array_diff_key instead of array_intersect_key Sep 11 '17 at 16:18

I find your solution rather complicated, so I would prefer this one:

foreach ($langs as$k => $v) { if (in_array($k, $allowed_langs)) {$result[$k] =$v;
}
}
var_export(\$result);


I' m incertain of which one is faster (and I tend to think this shouldn't be really important here), but I'm sure it's more simple and readable.

• Small comment: - "AS" -> "as" (highlighter doesn't highlight the CAPS). Jul 27 '16 at 8:21
• @RuslanBes Not sure what you address about highlighter: is it the SO's one? Anyway, I'm not initially partisan for this capitalization: I only resigned using it because it seems to be somewhat part of shared best practices, like for TRUE, FALSE, and NULL... and probably some other ones I don't have in mind at this time. Jul 27 '16 at 12:45
• @cFreed PSR actually recommends not using caps for true, false, null or as - php-fig.org/psr/psr-2 Jul 27 '16 at 16:11
• @cFreed it's just my perfectionism. If you write as then the SO highlighter will make it blue like foreach and if. Now it thinks apparently that it's a constant. Upvoted it anyway Jul 27 '16 at 20:51
• @cFreed as C Ivemy said, it's actually the opposite in terms of "best practice" Jul 27 '16 at 21:58