PHP foreach Equivalent In JavaScript

31st March 2009 - 2 minutes read time

If you are familiar with PHP you will have come across the for loop at some point. When learning JavaScript it is important to remember that it also has the ability to do the equivalent of the PHP forloop.

The following snippet shows the creation of an array of things that can't be referenced by a normal for loop due to the odd numbering of the keys.

var arrThings= new Array();
arrThings[3] = 'thing 1';
arrThings[42] = 'thing 2';
arrThings[47] = 'thing 3';
arrThings[32] = 'thing 4';
var output = '';
for ( var thing in arrThings ) {
 output += arrThings[thing];


The variable thing is now the iterator and will iterate through each element of the array. By using this code you no longer have to include code that thinks about the length of the array.

Add new comment

The content of this field is kept private and will not be shown publicly.