Last Updated: February 25, 2016
·
535
· alioygur

Fibonacci

<?php

/**
 * Get value of index in fibonacci series
 *
 * @author Ali OYGUR <alioygur@gmail.com>
 * @param  int $n index number
 * @return int    value o index
 */
function fibonacci($n) {

    // 0,1
    $fib = array(0,1);
    // 1,1
    //$fib = array(1,1);

    for($i = 1; $i < $n; $i++) {
        $fib[] = array_sum($fib);
        $fib   = array_slice($fib, 1, NULL, TRUE);
    }
    return $fib[$n];
}

/**
 * Get fibonacci series
 *
 * @author Ali OYGUR <alioygur@gmail.com>
 * @param  int $n series length
 * @return array  the fibonacci series
 */
function fibonacci_series($n) {

    // use 0,1 series
    $fib = array(0,1);
    // OR you can use 1,1 series
    //$fib = array(1,1);

    for($i = 1; $i < $n; $i++) {
        $fib[] = array_sum(array_slice($fib, -2));
    }

    return $fib;
}

// End of file
?>

https://gist.github.com/4534190