Generating Fibonacci Series in PHP

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones. Here’s a PHP example to generate the Fibonacci series:

Mathematical Example:

0 1 1 2 3 5 8 13
Here,

0 + 1 = 1
1 + 1 = 2
1 + 2 = 3
2 + 3 = 5
3 + 5 = 8
5 + 8 = 13

PHP Example:

<?php
function generateFibonacci($number)
{
    $num1 = 0;
    $num2 = 1;
    $num3 = 0;

    echo "<h3>Fibonacci series for the first $number numbers.</h3>";
    echo "\n";  // Line Break
    echo $num1 . ' ' . $num2 . ' ';  // Print the first two numbers

    for ($i = 0; $i < $number; $i++) {
        $num3 = $num2 + $num1;
        echo $num3 . ' ';
        $num1 = $num2;
        $num2 = $num3;
    }
}

// Allow user input for dynamic Fibonacci series generation.
generateFibonacci(8);
?>

Output:

The above PHP code will produce the following output:

Fibonacci series for the first 8 numbers.
0 1 1 2 3 5 8 13

Explanation:

  1. Variable Initialization:
    • $number: The specified number of elements in the Fibonacci series.
    • $num1 and $num2: The first two numbers of the series.
    • $num3: Variable to store the next number in the series.
  2. Loop Logic:
    • The for loop generates the Fibonacci series by adding the previous two numbers.