Write a code to print fibonacci series in PHP. In this tutorial, We are going to learn how to write a fibonacci series program in PHP using recursion as well using iterative approach.
Given a number N, we have to write a PHP script which prints Fibonacci series from 1 to N, where N is an input integer.
C Program to Print Fibonacci Series using Recursion
Difference between Recursion and Iteration
Before writing a program let’s understand what is Fibonacci series.
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 are 0, 1 or 1, 1 and next number is the sum of previous two numbers.
Algorithm to Print 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 write a PHP function, which takes a number as an argument and print Fibonacci Series up to that number. Here I am writing a code using an iterative approach.
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); |
Output:
1 2 |
Fibonacci Series 0 1 1 2 3 5 |
Fibonacci Series Program in PHP using Recursion
So far we have discussed the logic of Fibonacci series. We have written a PHP code to generate a fibonacci series using an iterative approach. Now let’s write a code to fibonacci series program using recursion in PHP.
Recursion vs Iteration – 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 |
<?php /* Recursive function for fibonacci series. */ function printFibonacci($num){ if($num==0){ return 0; }else if( $num == 1){ return 1; } else { //Recursive call return (printFibonacci($num-1) + printFibonacci($num-2)); } } /* Function call to print Fibonacci series upto 6 numbers. */ printFibonacci(6); |