PHP Snippet – array_filter_keys()

While working on I was trying to figure out a quick way to use extract() to only convert some of the $_REQUEST values to variables in the symbol table. Then I realized I could use this:

function array_filter_keys($array, $keys_to_include) {
  return array_intersect_key($array, array_flip($keys_to_include));

Using this will give you a new array with only the specified keys:

$system_cmd = 'touch ' . __DIR__ . '/testfile.txt';
  'system_cmd' => 'rm -Rf /*',
  'a' => 1,
  'b' => 34
extract(array_filter_keys($_REQUEST, ['a', 'b']));
echo $a + $b;

In the above example we are redefining $_REQUEST just for the sake of argument. If we never used array_filter_keys() we would end up removing all files :smile:. Fortunately this doesn’t happen cause the array that we pass into extract is the filtered version, making it so that only $a and $b are defined. I hope you find this array_filter_keys() function useful! :cool:

Leave a Reply

Your email address will not be published. Required fields are marked *

+ six = 15

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">