Robson » Code » PHP » Fibonacci

 
<?
 
// fibonacci sequence displayer v1.0
 
// return an array containing the first [length] numbers of the fibonnaci sequence
function fibonacci($length)
{
   // if they just want the first number
   if ($length < 2)
       // return that
       return array(0);
   else
   {
       // start the sequence with zero and one
       $sequence = array(0, 1);
       // loop from the third number in the sequence until no more are needed
       while(count($sequence) < $length)
           // add the sum of the number before and before that
           $sequence[] = $sequence[count($sequence)-1] + $sequence[count($sequence)-2];
       // return the sequence array
       return $sequence;
   }
}
 
// example use
echo implode(', ', fibonacci(25));
 
?>
 
© 2004-17 robson | cc unless stated