Learn how to implement the Fibonacci series in PHP. This tutorial explains how to code a PHP Fibonacci series with examples. Understanding this concept will improve your understanding of recursion and loops.



What is a Fibonacci Series?

The Fibonacci series is a numerical sequence in which each number is the sum of the two numbers that come before it. Typically, the series begins with 0 and 1, following this pattern:

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

Generating the Fibonacci Series in PHP

There are two main ways to generate the Fibonacci series in PHP: using a for loop and using recursion.

Using a for Loop

The following code shows how to generate the Fibonacci series up to the 10th term using a for loop:

Example:

<?php
$first_num = 0;  
$second_num = 1;  
$n = 10; // Number of elements you want in the series
echo "Fibonacci Series: $first_num, $second_num";  

for($i = 2; $i < $n; $i++) {  
    $next_num = $first_num + $second_num;  
    echo ", $next_num";  
    $first_num = $second_num;  
    $second_num = $next_num;  
}  
?>

Explanation:

In the above example, the variables $first_num and $second_num are initialized to hold the starting numbers of the Fibonacci sequence—0 and 1, respectively. The variable $n sets the desired length of the series. Within the for loop, $next_num is calculated as the sum of $first_num and $second_num. These two variables are then updated in preparation for the next iteration, ensuring the series continues to generate accurately.

Using Recursion

The following code shows how to generate the Fibonacci series up to the 10th term using recursion:

Example:

<?php
function fibonacci($n, $first_num = 0, $second_num = 1) {
    if($n == 0) {
        return;
    }
    echo $first_num . ", ";
    $next_num = $first_num + $second_num;
    fibonacci($n - 1, $second_num, $next_num);
}

$n = 10; // Number of elements you want in the series
echo "Fibonacci Series: ";
fibonacci($n);
?>

Explanation:

In the above example, the fibonacci function primarily requires one argument, $n, which specifies the length of the Fibonacci sequence to generate. The other two arguments, $first_num and $second_num,  initialize and update the sequence. These are set by default to 0 and 1, the starting numbers of the Fibonacci sequence. The function uses recursion to call itself, decrementing $n and updating the sequence numbers until $n reaches zero, thereby completing the series. 

Conclusion

Generating a Fibonacci series in PHP is a straightforward task. You can use either a for loop or recursion based on your project's needs. Both methods explained in this tutorial are efficient and help you understand the core concepts of programming and PHP.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram