Fibonacci Series Program in PHP

The Fibonacci series are the sequence of number in which the next number is the sum of the previous two numbers. Fibonacci series was known hundreds of years before. The "Fibonacci" name came from the nickname "Bonacci".

We can easily remember Fibonacci Sequence using the Fibonacci Day, which is November 23rd. As 23rd November has the digits "1, 1, 2, 3" which is part of the sequence.

Fibonacci Series Program in PHP

In the above image, the first two numbers are 0 and 1. So, according to the Fibonacci rule the third number is 1 (sum of 0 and 1). The fourth number is 2 and so on.


0 + 1 = 1 // 0, 1, 1
1 + 1 = 2 // 0, 1, 1, 2
1 + 2 = 3 // 0, 1, 1, 2, 3
2 + 3 = 5 // 0, 1, 1, 2, 3, 5

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





Fibonacci Series Program using For Loop

Here, you will learn how to print Fibonacci series using for loop in PHP. In this below code, $f1 contains first number, i.e., 0 and $f2 contains second number, i.e., 1 and $n contains total Fibonacci series number count.

<?php
    $f1 = 0;
    $f2 = 1;
    $n = 30;
    echo $f1;
    echo '<br/>';
    echo $f2;
    for($i = 1; $i <= $n; $i++) {
        $f3 = $f1 + $f2;
        $f1 = $f2;
        $f2 = $f3;
        echo $f3 ."<br />"; 
    }
?>

Output of the above code



0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269



Fibonacci Series Program using Recursive Function

Recursion function is a function which is call itself.

<?php   
echo "<h2>Fibonacci series upto 20 - </h2>";  
echo "\n\n";  
$n = 15;  

/* Recursive function  */  
function recursive($n){  
    if($n == 0){  
		return 0;  
    }
	else if( $n == 1)
	{  
		return 1;  
	}  
	else {  
		return (recursive($n-1) + recursive($n-2));  
	}   
}  
/* Call Function */  
for ($i = 0; $i < $n; $i++){  
	echo recursive($i);  
	echo "\n";  
}  
?>

Output of the above code

Fibonacci series upto 20 -

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377




Related Articles

PHP count average word length and characters in a text file
How to create a multiple choice questions and answers in PHP
PHP Logging Errors Into a File
Date Timestamp Formats in PHP
PHP Programming Error Types
Dynamically Add/Delete HTML Table Rows Using Javascript
Submit a form data without page refresh using PHP, Ajax and Javascript
PHP Server Side Form Validation
How to add google reCAPTCHA v2 in registration form using PHP
Complete HTML Form Validation in PHP
Simple star rating system using PHP, jQuery and Ajax
jQuery File upload progress bar with file size validation




Read more articles


General Knowledge



Learn Popular Language