1

I'm trying to unset a key in all objects in an array of objects (basically removing any passwords), doing this:

    foreach ( $data['users'] as $user) {
        unset($user['password']);
    }

But it seems it doesn't effect the 'original' data ... how do I do this by reference (or whatever it takes to make this work as 'expected' – by which I mean, the key is removed from all objects in the original array)?

0

3 Answers 3

2

You can pass the $user as reference like this :

// check this --------------v
foreach ( $data['users'] as &$user) {
    unset($user['password']);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Weird, I tried this initially but couldn't make it work. Now it 'somehow' does ... probably something else broke it at that time, thanks.
2

Try:

foreach ( $data['users'] as $key => $user) {
    unset($data['users'][$key]['password']);
}

Or

foreach ( $data['users'] as &$user) {
    unset($user['password']);
}

Comments

0

My suggestion:

array_walk($data['users'], function(&$a) {unset($a['password']);});

2 Comments

So, is there a performance gain compared to the other solutions, or? It seems from other peoples tests, that foreach is faster ... One example here: ktorides.com/2015/02/php-array_walk-vs-foreach And there are others …
I don't know if foreach is faster or slower than array_walk. Maybe with a small array the difference is negligible, so the problem doesn't exist. Usually, I like nonconformist solutions, in order to learn something more.

Your Answer

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