Meler Lawler
Meler Lawler

Reputation: 175

Should I unset both `$key` and `$value` after every foreach statement?

All the answers I've found only talk about unsetting $value except one, which wasn't clear to me. So here I am. Say I have the line:

foreach ($data as $key => $value)
    {
    // do stuff
    }

Should I put these two lines after?

unset($key);
unset($value);

Or can I omit unset($key)? Also, is it recommended to ALWAYS use unset after every foreach? Say I have nested foreach loops, like this:

foreach ($data as $key => $value)
    {
        foreach ($data[$key] as $key => $value)
        {
        // do stuff
        }
        unset($key);
        unset($value);
    }
    unset($key);
    unset($value);

Would the nested unset() functions interfere with the highest level foreach? In other words, are the nested $key and $value the same as the highest level $key and $value?

Upvotes: 1

Views: 65

Answers (1)

GrumpyCrouton
GrumpyCrouton

Reputation: 8621

The solution to your problem is easier than you think it is.

Simply change the variable names for your nested loop, like so:

foreach ($data as $key => $value) {
    foreach ($value as $subkey => $subvalue) {
        // do stuff
    }
}

With the above code, you can access the array data from $date[$key] (Which is actually equal to $value inside the parent loop) as $subkey and $subvalue respectively.

You can also still access the parent loop data anywhere inside the parent foreach loop with $key and $value respectively.

Upvotes: 2

Related Questions