This question already has an answer here:
I am attempting to mirror the behavior of newArray = oldArray
, with the caveat of excluding some key/values of the oldArray
, so something like newArray = oldArray - undesiredOldKeyValue
. I realize this is fully doable with a foreach
on the oldArray
and using an if
to see if the encountered key is desired or not, but I am interested in a simpler or more concise approach if possible.
A couple of things to keep in mind, I need to exclude key/value pairs based on key, not value. I do not want to modify the oldArray
in the process of doing this.
</div>
You may try to use array_filer. Something like:
$new_array = array_filter($old_array, function ($value, $key) {
// return false if you don't want a value, true if you want it.
// Example 1: `return $value != 'do not keep this one';`
// Example 2: `return !in_array($key, ['unwanted-key1', 'unwanted-key2', 'etc']);`
}, ARRAY_FILTER_USE_BOTH);
It will filters elements of an array using a callback function.