Unset elements using array keys

2019-09-09 22:09发布

问题:

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.

回答1:

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


回答2:

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.



标签: php arrays unset