Tag Archives: foreach

Foreach loops in C#

This tutorial explains how to use the foreach loop to go through each element in an array. A foreach loop is simpler and easier to use than a for loop if you want to loop through each and every element in an array. There is no need to use a counter, specify an increment, or a condition. The foreach loop will simply loop through every element in the array.

Foreach loops are written in a way that is easy to understand, for example:

foreach (string item in itemsList){
   Console.WriteLine(item);
}

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};

      // Store length of names array in variable
      int arrayLength = names.Length;

      // Go through each name in names array and display on new line
      foreach (string name in names) {
        Console.WriteLine(name);
      }
      // Wait for user input before quitting program
      Console.ReadLine();
    }
  }
}

Next tutorial: Methods

Foreach loops in PHP

This tutorial explains how to use the foreach loop to loop through each item (element) in an array. The foreach loop can only be used on arrays and objects in PHP. On each iteration of a foreach loop, the value of the current element being accessed is assigned to $value. Foreach loops can be used on both regular arrays and associative arrays.

Watch the video below and then scroll down to see the sample code.

The sample PHP code below shows how to use a foreach loop for both regular arrays and associative arrays:

<?php
  $normal_array = array("Mary","Bob","Joe","Tim");
  $assoc_array = array("Sarah"=>25,"Kim"=>18,"Alice"=>32,"Alan"=>17);

  // using a foreach loop on a regular array:
  foreach($normal_array as $value){
    echo "Name: $value</br>";
  }

  // using a foreach loop on an associative array:
  foreach($assoc_array as $key => $value){
    echo "$key's age is $value.</br>";
  }
?>