php
  1. php-fibonacci-series

PHP Fibonacci Series

In mathematics, the Fibonacci series is a sequence of numbers, starting with 0 and 1, in which each number is the sum of the two preceding ones. In PHP, we can generate the Fibonacci series using loops or recursive functions.

Syntax

function fibonacci($n)
{
    if($n == 0 || $n == 1) {
        return $n;
    }
    else {
        return (fibonacci($n-1) + fibonacci($n-2));
    }
}

Example

Let's take an example of generating a Fibonacci series of the first 10 numbers using a recursive function in PHP.

function fibonacci($n)
{
    if($n == 0 || $n == 1) {
        return $n;
    }
    else {
        return (fibonacci($n-1) + fibonacci($n-2));
    }
}

for ($i = 0; $i < 10; $i++) {
    echo fibonacci($i) . " ";
}

Output

The above code will generate the following output:

0 1 1 2 3 5 8 13 21 34

Explanation

In the above code, we define a recursive function fibonacci that takes an integer $n as its input and returns the nth number in the Fibonacci series. If $n is either 0 or 1, the function returns $n. Otherwise, it returns the sum of the two preceding numbers in the series (i.e., the (n-1)th and (n-2)th numbers) using a recursive call.

In the for loop, we iterate through the first ten numbers in the series (0-9) and call the fibonacci function with each number as its input. The output is then printed to the screen.

Use

The Fibonacci series has many mathematical and practical applications and is often used in programming to generate a sequence of numbers to be used in a variety of ways, such as:

  • Generating a unique series of numbers for random number generation
  • Computing parallelism and concurrency
  • Searching for the patterns in nature, plants, and animals
  • Cracking code of encrypted messages

Important Points

  • Fibonacci series is a sequence of numbers starting with 0 and 1 in which each number is the sum of the two preceding ones.
  • We can generate Fibonacci series in PHP by using loops or recursive functions.
  • Recursion is an efficient way of generating Fibonacci series but can be slower for large values of n.
  • Fibonacci series has various mathematical and practical applications in programming

Summary

In this article, we learned how to generate the Fibonacci series in PHP using a recursive function. The Fibonacci series is a sequence of numbers in which each number is the sum of the previous two. The series has various mathematical and practical applications in programming. We can generate the series in PHP by using loops or recursive functions, but recursion is an efficient way of doing it.

Published on: