开发者

Unset array element inside a foreach loop

So here is my code:

<?php

$arr = array(array(2 => 5),
             array(3 => 4),
             array(7 => 10));

foreach ($arr as $v) {
    $k = key($v);
    if ($k > 5) {
        // unset this element from $arr array
    }
}

print_r($arr);

// now I would like to get the array without array(7 => 10) member

As you can see, I start with an array of single key => value arrays, I loop through this array and get a key of the current element (which is a single item array).

I need to unset elements of the array with key higher than开发者_JAVA技巧 5, how could I do that? I might also need to remove elements with value less than 50 or any other condition. Basically I need to be able to get a key of the current array item which is itself an array with a single item.


foreach($arr as $k => $v) {
    if(key($v) > 5) {
        unset($arr[$k]);
    }
}


It is safe in PHP to remove elements from an array while iterating over it using foreach loop:

foreach ($arr as $key => $value) {
    if (key($value) > 5) {
        unset($arr[$key]);
    }
}


Use key() to get the first key from the sub-array.

foreach($arr as $k => $v) {
    if(key($v) > 5) {
        unset($arr[$k]);
    }
}


It's not really safe to add or delete from a collection while iterating through it. How about adding the elements you want to a second array, then dumping the original?


To unset array element we Used unset() and php function like below:

foreach($array as $key=>$value)
{
   if(key($value) > 5) 
   {
      unset($array[$key]);
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜