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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

return ! in_array($key, ['undesired-key1', 'undesired-key2', 'etc']);
The call to array_filter() needs a third argument in order to also pass the keys to the callback.
@axiac thanks, I added two examples!
@axiac haha thanks again!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.