PHP Script to print Fibonacci series

Friends, This is another school / college script for you. This php program could be useful for the Freshers who are searching for job as well.

<!DOCTYPE html>
<html>
    <head>
        <title>PHP Fibonacci Script</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
		<h2>PHP script to print Fibonacci series</h2>
		<h3>Enter the limit:</h3>
		<form method="post">
			<input type="text" name="limit" />
			<button name="submit" type="submit" >Print Fibonacci Series</button>
		</form>
		<br />
    </body>
</html>

<?php

	if(isset($_POST['submit'])){
	
	  $limit = 0;
	  if(isset($_POST['limit'])){
		$limit = $_POST['limit'];
	  }
      $first_num = 0;
	  $second_num = 1;
	  $next_num = 0;
	  
      //check the input if the value is greater than 0
      if($limit > 0){
        print $first_num . "<br>";
      }else{
        print "Value should be greater than 0";
      }

      //check if input is 1
      if($limit > 1){
        print $second_num . "<br>";
      }
      
      //if the input is > 2 then do then print fibonacci
      while($limit > 2)
        {       
           //add the first value and second to get the next value
           $next_num   = $first_num + $second_num;
           
           //assign second value to first
           //next value to second
           //to find the next series
           $first_num  = $second_num;
           $second_num = $next_num;
           
           //print the next value
           print $next_num . "<br>";
           
           //decrement the limit by one 
           $limit--;
        }
	}
	
?>

Thing you will learn from the above program will be:

  1. How to get the POST input value
  2. How to write While loop in PHP
  3. Logic for fibonacci series

Output of the above Fibonacci will be here:

fibo

And you can see the demo in here:

demo

Enjoy the day!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top