Core PHP

While Loops

A while loop can be used to loop over the a set of indices that typically represent an aritmetic sequence. While-each loops can be used to iterate over the entries of an array. We also have do-while loops that are like a while loop, except that they are always executed at least once. Here, we have an example of each type of loop.

WhileLoops.php

<?php

  // Counting while loop
  echo "While loop";
  $i = 1;
  while ($i < 11) {
    echo $i." ";
    ++$i;
  }
  echo "<br /><br />";

  // while each loop
  echo "While-each loop";
  $saApostles = Array("Peter", "Andrew", "James the Greater (the son of Zebedee)", "John", "Philip",
    "Bartholomew", "Matthew", "Thomas", "James the Less (the son of Alphaes)", "Simon the Zealot",
    "Judas (Thaddeus or Jude)", "Judas Iscariot");
  while (list ($key, $val) = each ($saApostles)) {
    echo $val."<br />";
  }
  echo "<br />";

  // do-while loop always execute at least once
  $bHavePair = false;
  srand();
  do {
    $j = (rand() % 12);
    $k = (rand() % 12);
    // We want make sure that two distinct apostles are selected
    if ($j != $k) {
      $bHavePair = true;
      echo "( ".$saApostles[$j].", ".$saApostles[$k]." )<br />";
    }
  } while(!$bHavePair);
?>
 

Output

 
 

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