Write a program to print fibonacci series upto N numbers. N is the number input by user. In this post, we’ll write fibonacci series code in PHP both using iterative and recursive approach.

Generate Fibonacci Series using Recursion.

Difference between Recursion and Iteration.

Before writing program let’s understand what is **Fibonacci series**.

The Fibonacci series is the series of numbers such as 0, 1, 1, 2, 3, 5,…… in which the next number is the **sum of two previous numbers**.

In Fibonacci series the first two numbers is 0, 1 or 1, 1 and next number is the sum of previous two numbers.

**Logic of Fibonacci Series**

i) Initialize first and second number.

first = 0 and second = 1.

ii) Print both first and second number.

iii) Loop from index 2 to N. So third number is the sum of first and second.

1 2 3 4 5 6 7 | for($i = 2; $i < $n; $i++) { $third = $first + $second; echo $third; $first = $second; $second = third; } |

## Print Fibonacci Series in PHP using Iterative Approach

Let’s create a simple PHP function, which takes number as an argument. I am using iterative approach to solve this problem.

Difference between recursion and iteration.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /* Function accepts number as an argument. */ function printFibonacci($n) { $first = 0; $second = 1; echo "Fibonacci Series \n"; echo $first.' '.$second.' '; for($i = 2; $i < $n; $i++){ $third = $first + $second; echo $third.' '; $first = $second; $second = $third; } } /* Function call to print Fibonacci series upto 6 numbers. */ printFibonacci(6); |

I print the series upto six numbers, you can pass any number as an argument.

Output:

1 2 | Fibonacci Series 0 1 1 2 3 5 |

## Print Fibonacci Series in PHP using Recursion

So far we have discussed the logic of Fibonacci series. I have written PHP code to generate this series using iterative approach. Here is a recursive code to generate this series.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php /* Print fiboancci series upto 8 elements. */ $num = 8; /* Recursive function for fibonacci series. */ function fibonacci($num){ if($num==0){ return 0; }else if( $num == 1){ return 1; } else { return (fibonacci($num-1) + fibonacci($num-2)); } } /* Call Function. */ for ($i = 0; $i < $num; $i++){ echo fibonacci($i); echo "\n"; } |