fibonacci-array.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>PHP Arrays</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 (indexed from 1 for convenience)
 * and prints them in reverse order.
 */
    $fib = array();
    $fib[1] = 1;		// prime the list
    $fib[2] = 1;
    $n = 2;			// running index
    while( $fib[$n] < 100 )
    {
      $fib[$n+1] = $fib[$n] + $fib[$n-1]; // compute next Fibonacci number
      $n++;
    }
    // At this point $fib[$n] > 100 so don't print it
    for($i=$n-1; $i>0; $i--)
    {
      print $fib[$i];
      if( $i > 1 ) { print ", "; }
    }
  ?>
  </p>
  </body>
</html>