PHP Fibonacci Sequence

There is actually a way to calculate a Fibonacci number without iteration by using rounding:

http://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding

function getFib($n)
{
    return round(pow((sqrt(5)+1)/2, $n) / sqrt(5));
}

Simple function of fibonacci

function fibonacci($n,$first = 0,$second = 1)
{
    $fib = [$first,$second];
    for($i=1;$i<$n;$i++)
    {
        $fib[] = $fib[$i]+$fib[$i-1];
    }
    return $fib;
}
echo "<pre>";
print_r(fibonacci(50));

In this example, I am using a for loop and limiting the length to 10:

$x = 0;    
$y = 1; 

for($i=0;$i<=10;$i++)    
{    
    $z = $x + $y;    
    echo $z."<br />";         
    $x=$y;       
    $y=$z;     
}   

Output:
1
2
3
5
8
13
21
34
55
89
144

Tags:

Php

For Loop