Practical-03
Write a PHP program to display the Fibonacci series.
Introduction
The Fibonacci series has been used for centuries in mathematics and is one of the most well-known and important series in modern mathematics. It begins with two numbers, 0 and 1, and the next number in the sequence is the sum of the two preceding numbers. This sequence continues to infinity. It can be used to calculate a wide range of geometric shapes and can also be used to solve problems involving probability, compound interest, and other mathematical calculations. Despite its complexity, it is surprisingly easy to generate a Fibonacci series using PHP.
Code
<?php
// Initialize the sequence with 0 and 1
$first = 0;
$second = 1;
// Use the variables to generate the Fibonacci sequence
$numbers = array($first, $second);
for ($i = 2; $i < 20; $i++) {
// Use the summation of the previous two numbers
// to generate the next number in the sequence
$next = $first + $second;
// Add the new number to the sequence
array_push($numbers, $next);
// Update the variables for the next iteration
$first = $second;
$second = $next;
}
// Output the sequence
echo implode(', ', $numbers);
Output
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181
Explanation
The code above creates a simple PHP function which generates a Fibonacci sequence of 20 numbers. First, two variables are initialized - $first and $second - which contain the first two numbers in the sequence, 0 and 1. Next, a for loop is used to iterate 20 times, generating the next number in the sequence in each iteration. The new number is calculated as the sum of the previous two numbers, then added to the array of numbers. Lastly, the array of numbers is outputted with the implode function.