Fibonacci sequence is a infinite series of numbers where each item is the sum of the two preceding ones, starting from 0 and 1.
I have written 2 examples
The first function returns a Fibonacci sequence, stopping when we reach given upper limit:
<?php
$upper_limit = 4000000;
echo implode(', ', fibonacci($upper_limit));
function fibonacci(int $max, array $buffer=[]) : array
{
// if we have no buffer we initialize it with 0 and 1
if (empty($buffer)) {
$buffer = [0, 1];
}
// we get current index
$index = count($buffer) - 1;
// calculate next number
$next = $buffer[$index] + $buffer[$index-1];
//if we reached upper limit we return the array containing the sequence
if($max < $next) {
return $buffer;
}
// (otherwise)
// we put new item in array
$buffer[] = $next;
// we run again the function with the new buffer
return fibonacci($max, $buffer);
}
The second one prints N numbers of the sequence.
<?php
$n = 50;
echo implode(', ', fibonacci($n));
function fibonacci(int $n, array $buffer=[]) : array
{
// edge cases
if($n==0) return [];
if($n==1) return [0];
// if we have no buffer we initialize it with 0 and 1
if (empty($buffer)) {
$buffer = [0, 1];
}
// we get current index
$index = count($buffer) - 1;
// calculate next number
$next = $buffer[$index] + $buffer[$index-1];
// if we have N numbers
if($n === ($index+1)) {
return $buffer;
}
// (otherwise)
// we put new item in array
$buffer[] = $next;
// we run again the function with the new buffer
return fibonacci($n, $buffer);
}
Motorcycle rider
American football player
DIY enthusiast
Web developer on free time