PHP Program to Print Fibonacci Series
for ($i = 0; $i < $n; $i++) { echo $a; $next = $a + $b; $a = $b; $b = $next; } where $a and $b start as 0 and 1.Examples
How to Think About It
Algorithm
Code
<?php $n = 10; // Number of terms $a = 0; $b = 1; for ($i = 0; $i < $n; $i++) { echo $a . " "; $next = $a + $b; $a = $b; $b = $next; } ?>
Dry Run
Let's trace printing 5 Fibonacci numbers through the code
Initialize variables
$a = 0, $b = 1, $n = 5
First iteration (i=0)
Print 0, next = 0 + 1 = 1, update $a=1, $b=1
Second iteration (i=1)
Print 1, next = 1 + 1 = 2, update $a=1, $b=2
Third iteration (i=2)
Print 1, next = 1 + 2 = 3, update $a=2, $b=3
Fourth iteration (i=3)
Print 2, next = 2 + 3 = 5, update $a=3, $b=5
Fifth iteration (i=4)
Print 3, next = 3 + 5 = 8, update $a=5, $b=8
| Iteration | Next | a | b | |
|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 1 |
| 1 | 1 | 2 | 1 | 2 |
| 2 | 1 | 3 | 2 | 3 |
| 3 | 2 | 5 | 3 | 5 |
| 4 | 3 | 8 | 5 | 8 |
Why This Works
Step 1: Start with first two numbers
The Fibonacci series always begins with 0 and 1, so we set $a = 0 and $b = 1.
Step 2: Print current number
In each loop, we print the current number stored in $a because it represents the next number in the series.
Step 3: Calculate and update
We find the next number by adding $a and $b, then update $a and $b to move forward in the sequence.
Alternative Approaches
<?php function fib($n) { if ($n == 0) return 0; if ($n == 1) return 1; return fib($n - 1) + fib($n - 2); } $n = 10; for ($i = 0; $i < $n; $i++) { echo fib($i) . " "; } ?>
<?php $n = 10; $fib = [0, 1]; for ($i = 2; $i < $n; $i++) { $fib[$i] = $fib[$i - 1] + $fib[$i - 2]; } foreach ($fib as $num) { echo $num . " "; } ?>
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs n times, each iteration does constant work, so time is O(n).
Space Complexity
Only a few variables are used to store numbers, so space is O(1).
Which Approach is Fastest?
The iterative loop approach is fastest and most memory efficient compared to recursion or array storage.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loop | O(n) | O(1) | Fast and memory efficient |
| Recursive function | O(2^n) | O(n) | Simple but slow for large n |
| Array storage | O(n) | O(n) | When you need all numbers stored |