Zak Henry
Zak Henry

Reputation: 2185

PHP arrays - simple way to change value of relative location in deep associative array

I have a script that is handling an array in $_SESSION, however I want to change one specific value within that array. I could go the nested foreach route, however I think I am missing a simpler solution.

The branch of the array that I want to change looks like

$_SESSION['roles'][$group][$role]['status'] = 'disabled';

This is of course easy to change if I know the $group and $role variables, however for the script I am trying to write I simply want to change the first instance of ['status'] to 'active'. (That is the status of the first $role in the first $group of the $_SESSION['roles'] array

I tried

$_SESSION['roles'][key($_SESSION['roles'])][key(current($_SESSION['roles']))]['status'] = 'active';

which works, but this also seems clumsy. Am I missing a simple function here?

Upvotes: 0

Views: 295

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318518

There's no better solution. "Relative/sequential access" and "associative arrays" don't fit together very well anyway.

Btw, depending on what you did with the array before you'll have to reset() it sokey()` returns the first key.

Edit: For the first part you could replace $_SESSION['roles'][key($_SESSION['roles'])] with reset($_SESSION['roles']). That returns the first element of the array. If PHP allows you to pass a non-variable to reset() you can do the same for the inner array, i.e. reset(reset($_SESSION['roles'])).

Upvotes: 2

Related Questions