Unset array element inside a foreach loop
Posted
by Richard Knop
on Stack Overflow
See other posts from Stack Overflow
or by Richard Knop
Published on 2010-05-17T20:05:15Z
Indexed on
2010/05/17
20:10 UTC
Read the original article
Hit count: 164
php
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 sinwgle key => value arrays, I loop thorugh 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 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.
© Stack Overflow or respective owner