Skip to content

Instantly share code, notes, and snippets.

@nvjkmr
Last active March 21, 2017 14:42
Show Gist options
  • Save nvjkmr/e7df30ac8565e0afc97598a246e9ede6 to your computer and use it in GitHub Desktop.
Save nvjkmr/e7df30ac8565e0afc97598a246e9ede6 to your computer and use it in GitHub Desktop.
Filter associative array with an array of keys
<?php
$data = array(
'key1' => 'val1',
'key2' => 'val2',
'key3' => 'val3',
'key4' => 'val4',
'key5' => 'val5',
'key6' => 'val6',
'key7' => 'val7',
);
$wanted = array('key2', 'key5', 'key7');
$flipped = array_flip($wanted);
$result = array_intersect_key($data, $flipped);
/*
$result will have the following:
'key2' => 'val2'
'key5' => 'val5'
'key7' => 'val7'
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment