Simple one, I was just wondering if there is a clean and eloquent way of returning all values from an associative array that do not match a given key(s)?
JavaScript
x
$array = array('alpha' => 'apple', 'beta' => 'banana', 'gamma' => 'guava');
$alphaAndGamma = arrayExclude($array, array('alpha'));
$onlyBeta = arrayExclude($array, array('alpha', 'gamma'));
function arrayExclude($array, Array $excludeKeys){
foreach($array as $key => $value){
if(!in_array($key, $excludeKeys)){
$return[$key] = $value;
}
}
return $return;
}
This is what I’m (going to be) using, however, are there cleaner implementations, something I missed in the manual perhaps?
Advertisement
Answer
You could just unset
the value:
JavaScript
$alphaAndGamma = $array;
unset($alphaAndGamma['alpha']);
Edit: Made it clearer. You can copy an array by assigning it to another variable.
or in a function:
JavaScript
function arrayExclude($array, Array $excludeKeys){
foreach($excludeKeys as $key){
unset($array[$key]);
}
return $array;
}