For Each Loop Code Examples

This post continues with examples in multiple languages of various coding routines. It’s goal is to assist someone transitioning from one language to another.

In this example we cover the for each loop.

PHP


$listOfItems = Array ('Green', 'Red', 'Blue', 'Orange');
foreach ($listOfItems as $colour) {
  echo 'colour = ' . $colour . "\n";
}

C#


ArrayList listOfItems = new ArrayList(10);
listOfItems.Add('Green');
listOfItems.Add('Red');
listOfItems.Add('Blue');
listOfItems.Add('Orange');

foreach (string colour in listOfItems) {
Response.Write(“colour = ” + colour + “\n”);
}

VB .NET

 

 

Objective-C


// Build an array of strings
NSMutableArray *listOfItems = [[NSMutableArray alloc] init];
[listOfItems addObject:@"Green"];
[listOfItems addObject:@"Red"];
[listOfItems addObject:@"Blue"];
[listOfItems addObject:@"Orange"];

for(NSString *colour in listOfItems)
NSLog([NSString stringWithFormat:@”colour=%@”, colour]);

Leave a Reply