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>";
  }
?>