The Fibonacci series starts with 0, and 1. a next number of the Fibonacci series is generated by adding the previous two numbers.
<?php
$a=0;
$b=1;
$num=0;
echo "fibonacci series for 10 element are:</br>";
echo $a.' '.$b;
while($num<8)
{
$next=$a+$b;
echo ' '.$next;
$a=$b;
$b=$next;
$num++;
}
?>
fibonacci series for 10 element are: 0 1 1 2 3 5 8 13 21 34
<?php
$a=0;
$b=1;
echo "fibonacci series for 20 element are:</br>";
// print first two number
echo $a.' '.$b;
/*since we have already printed first two number */
//Now we only iterate for loop from 1 to 18.
for($num=1;$num<=18;$num++)
{
// add previous two number and store in next variable
$next=$a+$b;
echo ' '.$next;
$a=$b;
$b=$next;
}
?>
fibonacci series for 20 element are: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
In this example, you will take the length of series input from the user using HTML form and print the length of series by using a while loop.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Program to print fibonaccie series</title>
</head>
<body>
<form>
Enter the fibonacci size<input type="number" name="Fibonacci">
<input type="submit" value="submit" name="submitForm"></br></br>
</form>
</body>
</html>
<?php
if(isset($_GET["submitForm"]))
{
$num=$_GET['Fibonacci'];
$a=0;
$b=1;
echo "fibonacci series for ".$num." element are:</br>";
echo $a.' '.$b;
$i=0;
while($i<$num-2)
{
$next=$a+$b;
echo ' '.$next;
$a=$b;
$b=$next;
$i++;
}
}
?>
a step-by-step explanation of the Fibonacci series program is given below:
$_GET
method value will be set, and the if-statement
evaluates the true expression.$num
variable by using code $num=$_GET['Fibonacci'];
$a
and 1 in $b
. Now print the value of $a and $b.$a
and $b
, we iterate the while loop from 0
to less than $num - 2
.$next
variable by using code $next=$a+$b
;$next
value and copy the value of $b
into $a
and $next
into $b
.i
. a loop will break when i
value become $num-2
.