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.



Recent Comments