3

Trying to process an array and remove a specific associative array in a larger array set. The code I have now works in removing the specific sections locally, within the for loop, but doesn't effect the original $cursor array.

foreach($cursor as $key) {

    foreach($key as $value => $k){

        if ($value == 'user'){

            unset($k['confinfo']);
        }
    }   
}

Is it a GLOBAL variable problem? How to unset the original variable?

alyx
  • 2,593
  • 6
  • 39
  • 64

2 Answers2

5

Iterate over the original array by reference:

foreach($cursor as &$key) // added &

It's important to note than whenever you do this, it's a very good idea to follow the loop with an unset to destroy the reference:

foreach($cursor as &$key) {
    // ...
}
unset($key);

Personally I find this a little ugly (par for the course in PHP), but this way you eliminate the risk of reusing the name $key later on and causing all sorts of "interesting" effects.

Jon
  • 428,835
  • 81
  • 738
  • 806
3

The problem is that the $k you get in the loop is not the original array that $cursor contains, it's just a copy that gets destroyed once the loop goes into the next round. To really remove the confinfo index from $cursor you need to start with $cursor and reference work your way down.

Replace

unset($k['confinfo']);

with

unset($cursor[$key][$value]['confinfo']);

It's not as short as the other answer, but it shows better what's going on and is thus easier to debug and extend later.

Wolfgang Stengel
  • 2,867
  • 1
  • 17
  • 22