1

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.

yanman1234
  • 1,009
  • 9
  • 27

1 Answers1

0

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.

rap-2-h
  • 30,204
  • 37
  • 167
  • 263