# Fibonacci Series Program in PHP

In this post, you will learn different ways to write Fibonacci series programs using PHP.

The Fibonacci series are the sequence of numbers in which the next number is the sum of the previous two numbers. The Fibonacci series was well-known hundreds of years earlier. 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. 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 a 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 />";
}
?>``````

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 called by itself. In the given example, we call the recursion function to get the Fibonacci series. A recursion function continues until some condition is met to prevent it. That's why we use the if else statement to break the infinite recursion.

``````<?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