0

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.

4
  • is request your array? Commented Jul 30, 2014 at 9:40
  • In fact, any such "way" will be internally a loop. So why worry? Commented Jul 30, 2014 at 9:40
  • I think that I read somewhere, that array_* functions are slightly faster than for example foreach Commented Jul 30, 2014 at 9:46
  • or maybe not willem.stuursma.name/2010/11/22/… :-D but this is an old article for PHP 5.3.. Commented Jul 30, 2014 at 9:53

2 Answers 2

1
$result = array_diff_key($request, array_flip(['id', 'date', 'whatever']));
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

A loop by any other name... ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.