Introduction
In PHP, generating the Fibonacci series is a common beginner and interview-level question. It helps developers understand loops, recursion, and number patterns.
In this article, you will learn what the Fibonacci series is and how to implement it in PHP using different approaches.
What is the Fibonacci Series?
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding numbers.
The series starts with:
0, 1, 1, 2, 3, 5, 8, 13, 21…
Formula:
F(n) = F(n-1) + F(n-2)
- First number = 0
- Second number = 1
- Every next number = sum of previous two numbers
Syntax (General Logic)
To generate Fibonacci series:
- Initialize first two numbers (0 and 1)
- Add them to get next number
- Continue the process
Examples
Example 1: Fibonacci Using for Loop
<?php
$n = 10;
$a = 0;
$b = 1;
echo $a . " " . $b . " ";
for ($i = 2; $i < $n; $i++) {
$c = $a + $b;
echo $c . " ";
$a = $b;
$b = $c;
}
?>
Output:
Example 2: Fibonacci Using while Loop
<?php
$n = 10;
$a = 0;
$b = 1;
$count = 2;
echo $a . " " . $b . " ";
while ($count < $n) {
$c = $a + $b;
echo $c . " ";
$a = $b;
$b = $c;
$count++;
}
?>
Example 3: Fibonacci Using Recursion
<?php
function fibonacci($n) {
if ($n == 0) return 0;
if ($n == 1) return 1;
return fibonacci($n - 1) + fibonacci($n - 2);
}
for ($i = 0; $i < 10; $i++) {
echo fibonacci($i) . " ";
}
?>
Example 4: Fibonacci with User Input
<?php
$n = 5;
$a = 0;
$b = 1;
for ($i = 0; $i < $n; $i++) {
echo $a . " ";
$temp = $a + $b;
$a = $b;
$b = $temp;
}
?>
Example 5: Store Fibonacci in Array
<?php
$n = 10;
$fib = [];
$fib[0] = 0;
$fib[1] = 1;
for ($i = 2; $i < $n; $i++) {
$fib[$i] = $fib[$i - 1] + $fib[$i - 2];
}
print_r($fib);
?>
Real-Life Example
Scenario 1 : Population Growth Model
Fibonacci series is used to model population growth patterns.
Scenario 2: Financial Market Analysis
Traders use Fibonacci levels to predict stock price movements.
Scenario 3: UI/UX Design
Fibonacci ratios are used in layout design for better visual balance.
Common Mistakes
1. Wrong Initialization
$a = 1; $b = 1;
👉 Correct is 0 and 1.
2. Infinite Loop
Incorrect loop condition may cause infinite execution.
3. Wrong Formula
$c = $a * $b;
Should be an addition.
4. Recursion Without Base Case
Leads to infinite recursion.
5. Large Input in Recursion
Recursive approach is slow for large values.
Conclusion
The Fibonacci series in PHP is an essential concept for understanding sequences, loops, and recursion. It is widely used in programming, mathematics, and real-world applications.
By mastering Fibonacci logic, you can:
- Improve problem-solving skills
- Understand recursion deeply
- Write efficient algorithms