find the nth fibonacci number in php

To find the nth fibonacci number in PHP, we can use either recursion or dynamic programming approach.

Recursion method:

main.php
function fibonacciRecursive($n){
    if ($n <= 1) return $n;
    return fibonacciRecursive($n-1) + fibonacciRecursive($n-2);
}

echo fibonacciRecursive(7); // Output: 13
170 chars
7 lines

Dynamic Programming method:

main.php
function fibonacciDynamic($n){
    $fib = array(0, 1);
 
    for($i=2; $i<=$n; $i++){
        $fib[$i] = $fib[$i-1] + $fib[$i-2];
    }
    return $fib[$n];
}

echo fibonacciDynamic(7); // Output: 13
200 chars
11 lines

In both methods, we return the nth fibonacci number. The recursion method uses function calling to calculate the fibonacci number which can be slower than the dynamic programming approach. The dynamic programming method stores previously computed numbers in an array making it a faster approach.

gistlibby LogSnag