Core PHP

Looping Over Arrays

Typically, we want to loop over or step over all of the entries of an array and access each element in the array.

LoopOverArray.php

<?php
  // Create an empty array
  $saBeatitudes = array();

  // Filling the array via assignments
  $saBeatitudes[0] = "Blessed are the poor in spirit, for theirs is the kingdom of heaven.";
  $saBeatitudes[1] = "Blessed are they who mourn, for they shall be comforted.";
  $saBeatitudes[2] = "Blessed are the meek, for they shall inherit the earth.";
  $saBeatitudes[3] = "Blessed are they who hunger and thirst for righteousness, ".
    "for they shall be satisfied.";
  $saBeatitudes[4] = "Blessed are the merciful, for they shall obtain mercy.";
  $saBeatitudes[5] = "Blessed are the pure of heart, for they shall see God.";
  $saBeatitudes[6] = "Blessed are the peacemakers, for they shall be called children of God.";
  $saBeatitudes[7] = "Blessed are they who are persecuted for the sake of righteousness, ".
    "for theirs is the kingdom of heaven.";


  // Use a for loop to print each entry via the index
  echo "<b>For loop with Index Access:</b><br />";
  $iSize = count($saBeatitudes);
  for ($i = 0; $i < $iSize; ++$i) {
    // Braces signify the value of the variable
    echo "{$saBeatitudes[$i]}<br />";
  }
  echo "<br />";


  // Use a foreach loop to print each entry
  echo "<b>Foreach loop over Beatitudes:</b><br />";
  foreach ($saBeatitudes as $sBeatitude) {
    echo "{$sBeatitude}<br />";
  }
  echo "<br />";


  // Use a foreach loop to print each key with its value
  echo "<b>Foreach loop with Key=>Value Pairs:</b><br />";
  foreach ($saBeatitudes as $key => $value) {
    echo "{$key} => {$value}<br />";
  }
  echo "<br />";


  // Use a do-while loop with the current() and next().
  echo "<b>Do-while loop using current() and next():</b><br />";
  reset($saBeatitudes);
  $sBeatitude = current($saBeatitudes);
  do {
    echo "{$sBeatitude}<br />";
  } while ($sBeatitude = next($saBeatitudes));
  echo "<br />";
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.