PHP - Using foreach to Loop Through Values

Introduction

The simplest way to use foreach is to retrieve each element's value, as follows:

foreach ($array as $value) {
  // (do something with $value here)
}
// (rest of script here)

foreach loop continues to iterate until it has retrieved all the values in the array, from the first element to the last.

On each pass through the loop, the $value variable gets set to the value of the current element.

You can then do whatever you need to do with the value within the loop's code block.

Then, the loop repeats again, getting the next value in the array, and so on.

Demo

<?php

         $authors = array("A","B","C","D");

         foreach ($authors as $val) {
           echo $val."\n";
         }//from ww w.j  a  v  a 2 s .  c  o  m
?>

Result

You can use any variable name you like to store the value.

Any variable that you place after the as in the foreach statement gets assigned the current element's value.

Related Topic