Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unset array element inside a foreach loop

Tags:

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 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.

like image 531
Richard Knop Avatar asked May 17 '10 20:05

Richard Knop


People also ask

How do I remove an array from a forEach loop?

Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable. The behavior of this function depends on different things.

How do I remove an object from an array in forEach?

To remove element from array in forEach loop with JavaScript, we can use the array splice method. const review = ["a", "b", "c", "b", "a"]; review. forEach((item, index, arr) => { if (item === "a") { arr. splice(index, 1); } });

Can we remove an element by using forEach loop?

The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove . Therefore, the for-each loop is not usable for filtering.

How do you unset an array array?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.


1 Answers

foreach($arr as $k => $v) {     if(key($v) > 5) {         unset($arr[$k]);     } } 
like image 105
sasa Avatar answered Sep 25 '22 20:09

sasa