fibonacci-pushpop.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Fibonacci Numbers, Push/Pop Version</title>
    <meta charset="utf-8">
  </head>
  <body>
  <h1>Fibonacci Numbers Less than 100</h1>
  <h2>In Descending Order</h2>
  <p>
  <?php
/* Computes the famous Fibonacci sequence using a loop.
 * The recurrence is F_n+1 = F_n + F_n-1
 * This version stores them in an array, using push
 * and prints them in reverse order, using pop.
 * No explicit indexing needed here.
 */
    $fib = array();
    $fib1 = 1;
    $fib2 = 1;
    array_push($fib, $fib1);		// prime the list
    array_push($fib, $fib2);
    while( $fib2 < 100 )
    {
      $fib3 = $fib2 + $fib1;
      array_push($fib, $fib3);
      $fib1 = $fib2;
      $fib2 = $fib3;
    }

    // At this point last item > 100 so discard it
    array_pop($fib);
    print "There are " . count($fib) . " numbers: ";
    while( $fib ) {
      print array_pop($fib);
      if( $fib ) { print ", "; }
    }
  ?>
  </p>
  </body>
</html>