Search code examples
phpunset

How to unset a key in all objects in an array of objects?


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)?


Solution

  • You can pass the $user as reference like this :

    // check this --------------v
    foreach ( $data['users'] as &$user) {
        unset($user['password']);
    }