Print Fibonacci Series In PHP

Quick Summary

  • A recursive PHP function prints the Fibonacci series from the first two numbers you pass and a count of how many to print.
  • A static counter keeps its value across the recursive calls and stops the function once it passes the requested count.
  • Because the static counter never resets, a second call in the same script prints nothing; pass the counter as a fourth parameter instead.

The Fibonacci series starts with 0 and 1, and every number after that is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8 and so on. This PHP function prints the series with recursion: it is a recursive function that calls itself until a base case stops it. You pass the first two numbers and how many numbers you want to print.

PHP
function fibonacci ($old, $new, $end){
    static $start;
    $start = $start ?? 1;
    
    if ( $start>$end ){
        return;
    }

    $start++;
    echo $old." ";
    $_temp = $old+$new;
    $old = $new;
    $new = $_temp;

    fibonacci ($old, $new, $end);
}

fibonacci ( 0, 1, 10);

How it works

  • $old and $new hold the two most recent numbers of the series, and $end is how many numbers to print.
  • static $start is a static variable: it keeps its value between calls, so it works as a counter across the recursion. $start ?? 1 sets it to 1 on the first call. The ?? operator needs PHP 7 or later.
  • The base case: once $start is greater than $end, the function returns and the recursion stops.
  • Otherwise it increases the counter, prints $old followed by a space, and moves one step along the series: the new pair becomes $new and $old + $new. Then it calls itself with that pair.

fibonacci ( 0, 1, 10); prints the first ten numbers: 0 1 1 2 3 5 8 13 21 34. Change the third argument to print more or fewer.

One thing to watch

Because $start is static, it isn’t reset when the function finishes. If you call fibonacci() a second time in the same script, it prints nothing, since the counter is already past $end. If you need to call it more than once, pass the counter as a fourth parameter instead of using a static variable. Give that parameter a default value of 1, so calls like fibonacci( 0, 1, 10 ) keep working.

Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More