For Each Loops

Looping through each item in a collection is usually mandatory in programming, yet its fun and easy.

Here’s how to do it in different languages.

> php
foreach($array as $key => $value):
# use these variables
print($key.’ -> ‘.$value.’
‘);
endforeach;

> javascript/actionscript 3
for (var obj in window){
document.write( ‘window.’+obj +’ =>’+ window[obj] );
}

note the difference between the java and javascript’s loop is that the obj in js for returns the index of the item rather than the object itself.

> java 5
for (Object var : collection) {
// Do your stuff
}

> python
for item in container:

> shell
foreach {i j} {a b c d e f}

The fun part with looping a collection is that there isn’t a need to define indexes and limits for the loop. Sometimes in situations I have a fix loop but still prefer a for-each loop, I’ll create a predefined collection, perhaps a json array for javascript and associative collection for php, then run a for each loop over them.

This should be pretty old stuff and I’ve been thinking of this post long ago but really didn’t get my fingers typing until now.

2 Responses to “For Each Loops”


  1. 1 Tang Poh Kok

    Hey, don’t forget COBOL. It is English-like, clear and self-documentary. BTW, this is the simplest format.
    PERFORM UNTIL condition
    Statements
    Statements
    Statements
    ….
    END-PERFORM

  2. 2 Tang Poh Kok

    sorry, wrong example. Should be this:
    PERFORM VARYING X FROM 1 BY 1 UNTIL X > 5
    statement
    statement
    statement
    ….
    END-PERFORM

Leave a Reply