Yury Sitnikov
Yury Sitnikov

Reputation: 15

PHP: unset does not work in foreach

I am trying to use unset in a foreach loop, but it is not working.

My code:

$aggr = $_GET;
foreach($aggr as $key => $value)
{
        $pos_key = preg_replace('/dst_addr/', '', $key);
        // why this not works:
        unset($aggr[$key]);
        unset($aggr[$key.'_h'.$pos_key]);
}

In the second iteration my key is eq $key.'_h'.$pos_key, but this key should be deleted and isn't.

Upvotes: 1

Views: 717

Answers (1)

Ry-
Ry-

Reputation: 224886

PHP makes a copy of the array to iterate over it. Since you end up with an empty array anyway, use a stack:

$s = array_keys($_GET);

while($c = array_pop($s)) {
    $pos_key = str_replace('dst_addr', '', $key);

    $i = array_search($key . '_h' . $pos_key, $s);

    if($i !== false) {
        array_splice($s, $i, 1);
    }
}

Upvotes: 1

Related Questions