Skip to content

Instantly share code, notes, and snippets.

@CraigChilds94
Last active March 1, 2016 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CraigChilds94/d038e3a0b7d22311bea4 to your computer and use it in GitHub Desktop.
Save CraigChilds94/d038e3a0b7d22311bea4 to your computer and use it in GitHub Desktop.
Useful array functions.
<?php
/**
* Only get the values for keys which
* exist in the array.
*
* Example: array_only_keys(['a' => 'b', 'c' => 'd'], ['a']); // returns ['a' => 'b']
*
* @param Array $haystack The array you want values from
* @param Array|String $keys Array of keys, or a key which you want from the haystack
* @return Array
*/
function array_only_keys($haystack, $keys)
{
return array_filter($haystack, function($v, $k) use ($keys) {
if (!is_array($keys)) return $k == $keys && $v;
return in_array($k, $keys) && $v;
}, ARRAY_FILTER_USE_BOTH);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment