Recursive Method

A recursive solution involves defining a function that calls itself to solve subproblems. First, we call a function with number $n i.e. fibNumber($n), and then check if number is less then or equal to 1, then it returns number, otherwise it returns fibNumber($n – 1) + fibNumber($n – 2).

PHP




<?php
function fibNumber($n) {
    if ($n <= 1) {
        return $n;
    }
  
    return fibNumber($n - 1) + fibNumber($n - 2);
}
  
// Driver Code
$n = 10;
  
echo "The {$n}th Fibonacci number is: " 
    . fibNumber($n);
?>


Output

The 10th Fibonacci number is: 55



PHP Program for Nth Fibonacci Number

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. In this article, we will write a PHP program to find the Nth Fibonacci number.

Table of Content

  • Iterative Method
  • Recursive Method

Similar Reads

Iterative Method

First, we define a function that takes an integer $n as a parameter. Inside the function, we initialize two variables, $f1 and $f2 with 0 and 1 respectively. These represent the first two numbers in the Fibonacci sequence....

Recursive Method

...

Contact Us