PHP foreach Equivalent In JavaScript

31st March 2009 - 1 minute 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.

  1. var arrThings= new Array();
  3. arrThings[3] = 'thing 1';
  4. arrThings[42] = 'thing 2';
  5. arrThings[47] = 'thing 3';
  6. arrThings[32] = 'thing 4';
  8. var output = '';
  10. for ( var thing in arrThings ) {
  11. output += arrThings[thing];
  12. }
  14. alert(output);

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.