user3489744
user3489744

Reputation:

Unset elements using array keys

So I need to delete some array elements, is there easy way not including foreach loop?

$privateData = ['id', 'date', 'whatever'];

foreach($privateData as $privateField) {
    unset($request[$privateField]);
}

I tried to search array_map array_walk functions for examples but I did not find any.

Upvotes: 0

Views: 52

Answers (2)

deceze
deceze

Reputation: 522499

$result = array_diff_key($request, array_flip(['id', 'date', 'whatever']));

Upvotes: 1

Barmar
Barmar

Reputation: 782130

Here's how you do it using array_map:

array_map(function($privateField) use ($request) {
    unset($request[$privateField]);
}, $privateData);

You need to use the use option to access $request from the outer scope.

I don't know why you'd want to do it this way. The foreach loop is much clearer. But since you asked.

Upvotes: 0

Related Questions