Display Fibonacci Series in PHP

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code Examples
Iteration

What you’ll learn

  • The usual definition with seeds 0 and 1, and Fk = Fk-1 + Fk-2.
  • An n-term printer with clean separators.
  • A second pattern: print Fibonacci numbers up to a maximum value, plus live preview.

Overview

Fibonacci is a great example of a stateful loop: track the previous two terms, print one, then shift forward.

Two programs

First n terms and values up to a cap.

Live preview

Test first n terms quickly in-browser.

Rigor

Handle nonpositive term counts and explain growth limits.

Prerequisites

for loops, functions, and integer addition in PHP.

  • Know basic PHP function syntax and echo.
  • Understand that Fibonacci values grow very fast as terms increase.

What is the Fibonacci series?

Starting from 0 and 1, each next term is the sum of the previous two.

This pattern appears in counting problems, algorithm analysis, and many interview questions.

Recurrence Fk=Fk-1+Fk-2
Seeds 0, 1
Growth ∼ φk

Golden ratio bound

With φ = (1+√5)/2, Fibonacci values grow approximately like φk/√5, which explains rapid size growth.

First ten outputs

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Intuition

5+8 13
Rule
sum prior pair
(a,b) shift
Update
(a,b)←(b,a+b)

Takeaway: two variables are enough to print the sequence.

Live preview

First n terms using BigInt for exact browser output.

Try 1, 15, or 80. Capped at 500 terms.

Live result
Press “Print series”.

Algorithm

Goal: print first n Fibonacci terms, or all terms not exceeding a limit M.

Initialize

Set (first, second) = (0, 1).

Iterate

Print first, compute next = first + second, then shift (first, second) = (second, next).

📜 Pseudocode

Pseudocode
function print_first_n_fibonacci_terms(n):
    a = 0
    b = 1
    repeat n times:
        output a
        next = a + b
        a = b
        b = next
1

First n terms (n = 10)

Two-variable iterative Fibonacci in PHP with clean comma formatting.

php
<?php
function displayFibonacciTerms(int $n): void
{
    $first = 0;
    $second = 1;

    if ($n <= 0) {
        echo "Need a positive term count.\n";
        return;
    }

    echo "Fibonacci series up to {$n} terms: ";

    for ($i = 0; $i < $n; $i++) {
        if ($i > 0) {
            echo ", ";
        }
        echo $first;
        $next = $first + $second;
        $first = $second;
        $second = $next;
    }

    echo "\n";
}

displayFibonacciTerms(10);
?>

Explanation

Print current $first, then move the pair forward. Printing separator only after the first item avoids a trailing comma.

2

All terms ≤ 100

Use value cap as stopping rule instead of fixed term count.

php
<?php
function displayFibonacciUntil(int $maxVal): void
{
    $a = 0;
    $b = 1;

    if ($maxVal < 0) {
        echo "maxVal must be nonnegative.\n";
        return;
    }

    echo "Fibonacci numbers <= {$maxVal}: ";
    $firstOut = true;

    while ($a <= $maxVal) {
        if (!$firstOut) {
            echo " ";
        }
        $firstOut = false;
        echo $a;

        $next = $a + $b;
        $a = $b;
        $b = $next;
    }

    echo "\n";
}

displayFibonacciUntil(100);
?>

Explanation

The loop checks value-before-printing. First Fibonacci greater than 100 is 144, so output stops at 89.

Going faster (optional)

Matrix exponentiation. Good for finding single Fn in O(log n).

Doubling identities. Useful in competitive programming and modular arithmetic.

Interview: for printing series, prefer the simple O(n) iterative loop.

❓ FAQ

Each term is the sum of the two before it. With seeds 0 and 1, the series begins 0, 1, 1, 2, 3, 5, 8, 13, ...
Yes; some texts start at 1,1. That changes indexing only. The recurrence after seeds is the same.
Yes. Fibonacci grows exponentially, so integers can exceed normal limits for large term counts.
Naive recursion recomputes many values and is slow. Iteration is O(n) and uses constant extra space.
That means an empty series. You can print a message or nothing, based on your assignment style.
O(n) additions using the two-variable update.

🔄 Input / output examples

Change $n in Example 1 or $maxVal in Example 2.

n (terms)Last printed
10
21
1034
204181

Edge cases and pitfalls

Values grow quickly. Always validate input and be clear about seed/index convention in interviews.

Terms

n ≤ 0

Treat as empty/error according to your requirement.

Growth

Large values

Fibonacci can exceed normal integer capacity for high terms.

Recursion

Naive recursion

Avoid for long series because repeated calls make it very slow.

Indexing

Seed convention

This page uses 0, 1 seeds; mention if you use 1, 1.

⏱️ Time and space complexity

TaskTimeExtra space
First n terms (iterative)O(n)O(1)
All terms ≤ MO(k), where k is terms printedO(1)
Naive recursive fib(n)O(φn)O(n)

Summary

  • Core loop: print first, then shift pair using next = first + second.
  • Variants: fixed term count and value-bounded printing.
  • Watch-outs: nonpositive input, separator formatting, and large-value growth.
Did you know?

The ratio of consecutive values Fk+1/Fk (for positive Fk) approaches the golden ratio φ = (1+√5)/2 as k grows.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful