Short circuit Array.forEach like calling break

There’s no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.  Run code snippetExpand snippet JavaScript exceptions aren’t terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it. Use Array#some Instead, use Array#some:  Run code snippetExpand snippet This works because some returns true as soon as any of the … Read more

Form submission: PHP S_SESSION statements within a foreach loop

Let’s suppose I have the following PHP code which attempts to read from an array called $arr which takes on the values {fullname, studentnumber, email}. Upon submission of my HTML form, this PHP code will execute the foreach loop, and store the values posted to the page in the $_SESSION array. The above code doesn’t work as intended. If I … Read more

Is there a ‘foreach’ function in Python 3?

Every occurence of “foreach” I’ve seen (PHP, C#, …) does basically the same as pythons “for” statement. These are more or less equivalent: So, yes, there is a “foreach” in python. It’s called “for”. What you’re describing is an “array map” function. This could be done with list comprehensions in python:

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

Two options: Create a list of values you wish to remove, adding to that list within the loop, then call originalList.removeAll(valuesToRemove) at the end Use the remove() method on the iterator itself. Note that this means you can’t use the enhanced for loop. As an example of the second option, removing any strings with a … Read more

Difference between “as $key => $value” and “as $value” in PHP foreach

Well, the $key => $value in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2,… In PHP, associative arrays look like this: In the PHP code: $featured is the associative array being looped through, and as … Read more