“Foreach” style loop syntax for Perl, Php and Javascript
Jan.21, 2008 in
Development
I am always forgetting the syntax for foreach() loops in javascript. They actually don’t exist (not in their Perl or Php form anyway) and they differ in that they iterate over all the properties of an object, not an array. You can get some unexpected results if you aren’t careful.
In perl you do the following:
my @myArray = qw(One Two Three);
foreach my $item (@myArray)
{
print "$item\n";
}
In Php you do very similar – note the “foreach (array as item)” syntax:
$myArray = Array("One", "Two", "Three");
foreach ($myArray as $item)
{
print "$item\n";
}
In Javascript you use “for (var in object)” syntax:
var myArray = new Array("One", "Two", "Three");
for (item in myArray)
{
alert(item);
}

Leave a Reply