Skip to content

Instantly share code, notes, and snippets.

@itailulu
Created March 27, 2014 08:33
Show Gist options
  • Save itailulu/9802978 to your computer and use it in GitHub Desktop.
Save itailulu/9802978 to your computer and use it in GitHub Desktop.
Filter array
//returns keys and values of $arr if key exist in $keys
function filter_array(array $arr, array $keys){
$ret = array();
foreach ( $keys as $k ){
if (array_key_exists($k,$arr)){
$ret[$k] = $arr[$k];
}
}
return $ret;
}
/* EXAMPLE:
$arr = array(
"key1" => "val1",
"key2" => "val2",
"key3" => "val3",
"key4" => "val4",
"key5" => "val5",
"key6" => "val6",
"key7" => "val7",
"key8" => "val8",
);
echo "this is the original array:\n<pre>";
print_r($arr);
echo "</pre>\n";
echo "here are the keys (and values) you requested\n<pre>";
$keys = array(
"key1",
"key4",
"key7",
"key15",
);
print_r(filter_array($arr,$keys));
echo "</pre>";
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment