How to Remove Element from Array in Foreach Loop

How do you remove an array element in a foreach loop?

If you also get the key, you can delete that item like this:

foreach ($display_related_tags as $key => $tag_name) {
if($tag_name == $found_tag['name']) {
unset($display_related_tags[$key]);
}
}

How to remove element from array in forEach loop?

It looks like you are trying to do this?

Iterate and mutate an array using Array.prototype.splice

var pre = document.getElementById('out');

function log(result) {
pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'b', 'c', 'b', 'a'];

review.forEach(function(item, index, object) {
if (item === 'a') {
object.splice(index, 1);
}
});

log(review);
<pre id="out"></pre>

Remove item from array using foreach - JavaScript

I would not recommend this. The forEach function iterates over the array and when you remove the current or a previous item it will skip the next item in the array. That being said if you really want to remove an item despite the problems you will run into it is possible to remove an item with array.splice(data, 1).

How to delete object from array inside foreach loop?

foreach($array as $elementKey => $element) {
foreach($element as $valueKey => $value) {
if($valueKey == 'id' && $value == 'searched_value'){
//delete this particular object from the $array
unset($array[$elementKey]);
}
}
}

PHP removing elements from array in a foreach loop

If you only use one parameter on a foreach loop you are delivered the value of the occurance and not the key for the occurance.

Try this so that you are getting a key from the foreach loop and not a value

foreach($removeKeys as $key => $val) {
unset($orders_list[$key]);
echo $key;
}

How to remove an element of array in foreach loop?

If you want to remove elements, the better tool is grep:

@array = grep { !/O/ } @array;

Technically, it is possible to do with a for loop, but you'd have to jump through some hoops to do it, or copy to another array:

my @result;
for (@array) {
if (/O/) {
push @result, $_;
}
}

You should know that for and foreach are aliases, and they do exactly the same thing. It is the C-style syntax that you are thinking of:

for (@array) { print $_, "\n"; }        # perl style, with elements
for (my $x = 0; $x <= $#array; $x++) { # C-style, with indexes
print $array[$x], "\n";
}

how to remove object from array of objects in foreach loop php

I'm guessing the array was in JSON format? Anyways.. I fixed your invalid JSON so you should be able to see how it's done.

$json = '

[{
"id": 1,
"name": "Bob",
"category": "admin",
"email": "test1@test.com",
"phone": "123456789",
"gender": "male"
}, {
"id": 2,
"name": "John",
"category": "user",
"email": "john@test.com",
"phone": "123456789",
"gender": "male"
}, {
"id": 3,
"name": "Jane",
"category": "admin",
"email": "jane@test.com",
"phone": "123456789",
"gender": "female"
}]

';

$array = json_decode($json, true); //Fixed and converted JSON into PHP Assoc Array

foreach($array as $k=>$v) {
foreach ($array[$k] as $key=>$value) {
if ($key === "category" && $value === "user") { //If Value of 2D is equal to user and cat

unset($array[$k]); //Delete from Array
}
}
}

var_dump($array); //Output Array

Output

array(2) {
[0] => array(6) {
["id"] => int(1)["name"] => string(3)
"Bob" ["category"] => string(5)
"admin" ["email"] => string(14)
"test1@test.com" ["phone"] => string(9)
"123456789" ["gender"] => string(4)
"male"
}[2] => array(6) {
["id"] => int(3)["name"] => string(4)
"Jane" ["category"] => string(5)
"admin" ["email"] => string(13)
"jane@test.com" ["phone"] => string(9)
"123456789" ["gender"] => string(6)
"female"
}
}

Edit

*As @sevavietl pointed out in the comments, if any other element of the array was called user, then this would be removed. I've changed code to now test the key (category) as well as the value. *

Javascript removing elements in forEach

That is because your forEach loop is not able to loop through all 3 elements as you are removing one item inside the forEach loop.

So, say your forEach loop went through index 0 and than 1 where it removed index 1. At this point the length of array is changed to n-1 but the index inside the for loop is still the same.

In order to make a copy of an array so that it doesn't make changes in the original array.

Do this -

var tempArray = names.slice(0);

Instead of this -

var tempArray = names;

How can I remove an item from an array while I use forEach on this array?

What you will want to do is loop over the array in reverse:

let i = tests.length
while(i--) tests[i].testme()

Here it is in action:

//creating a test arrayvar tests = [];tests.push(new Test(1));tests.push(new Test(2));tests.push(new Test(3));tests.push(new Test(4));
function Test(n) { this.n = n;
this.testme = function() { if(this.n < 3) { tests.splice(tests.indexOf(this), 1); //remove me from the array tests please! console.log(this.n, "I got removed!"); } else { console.log(this.n, "I can stay!"); } } }

console.log("tests length: ", tests.length);
let i = tests.lengthwhile(i--) tests[i].testme()
console.log("tests length: ", tests.length); //output should now be 2

How do I remove an element in a list, using forEach?

You shouldn't modify the array you're looping on. You can produce a new one, though:

var newPeople = [];
people.forEach(function(p){
if(p.length <= 4){
newPeople.push(p);
}
});

Why you shouldn't modify array you're looping.



Related Topics



Leave a reply



Submit