search

Fibonacci Series PHP

Aug 29, 2024 pm 01:12 PM
php

If said in layman language, a Fibonacci Series is a series of elements formed or obtained, when the previous two elements are added to form the next element until we get the required series size. We usually start the Fibonacci Series with 0 and 1.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The series once formed, appears as below:

0, 1, 1, 2 ,3, 5, 8, 13, 21, 34

As stated above, the next number is obtained by adding up the previous two numbers.

  • The ‘2’ on the 4th position (nth position) in the above-given series, is obtained by adding its preceding two numbers[ [n-1] and n-2]), 1.
  • The ‘3’ is obtained by adding its preceding two numbers,2.
  • The ‘5’ is obtained by adding its preceding two numbers,3.
  • And so on.

Fibonacci Series in PHP and the Logic

Here we will see specifically obtaining the Fibonacci Series while we are working in a PHP environment. The difference is the format in which we will be coding, i.e. using a starting tag for a PHP script and its ending tag.

<?php …;
…;
…;
?>

This will help you to understand and learn how this Fibonacci series is generated in PHP using two methods which is the Iterative way and the Recursive way.

When we are given a number i.e ‘n’ which is the series size, we will try to find the Fibonacci Series up to the given number.

For example, if we are required to create Fibonacci for n=5, we will display elements till the 5th term.

Example #1

  • Input: n = 9
  • Output: 0 1 1 2 3 5 8 13 21

Example #2

  • Input: n=13
  • Output: 0 1 1 2 3 5 8 13 21 34 55 89 144

Logic in PHP

Logic is the same as stated above. Here we have given n=10, i.e. we need to find the elements till nth term. Thus we will keep on following our logic till we have n terms in our series.

Let us see one of the examples given above.

In one of the above example we have n=9 and Logic says that:

  • Initialize the first number as 0.
  • Initialize the second number as 1.
  • Print the first and second numbers.
  • The loop starts here.
  • For next element in the series i.e. 3rd element [nth element],we will be adding its immediate preceding two numbers [(n-1) and (n-2)] to get the next number in the series, like here, 0 + 1 = 1.

For n=3

  • n – 1 = 3 – 1 = 2nd element of the series = 1
  • n – 2 = 3 – 2 = 1st element of the series = 0 3rd element = (n-1) + (n-2) = 1 + 0 = 1

Thus, the third element in the series is 1.

  • Similarly according to the logic, to get the 4th element [n] of the series we need to add its preceding numbers e. (n-1) and (n-2) element.

Now at this point, ‘n’ is equal to ‘4’:

  • n – 1 = 4 – 1 = 3rd element of the series = 1
  • n – 2 = 4 – 2 = 2nd element of the series = 1 4th element = (n-1) + (n-2) = 1 + 1 = 2

Thus, we get our 4th element as 2.

Thus, for ‘n’ equals to 9, following the same logic as explained above we get sequence as, Fibonacci sequence is 0 1 1 2 3 5 8 13 21

PHP Series for Fibonacci Printing with Two Approaches

There are basically two famous versions on how we can write a program in PHP to print Fibonacci Series:

  • Without Recursion
  • With Recursion

As usual in PHP, we will be using the ‘echo’ statement to print the output.

1. The Non-Recursion Way

Also known as for using the Iteration. This is the approach where we will start the series with 0 and 1. After which we will print the first and second numbers. Following which we will start with our iteration using a loop, here we are using a while loop.

PHP script for printing first 10 Fibonacci Series elements.

Code:

<?php function Fibonacci($n)
{
$num1= 0;
$num2= 1;
$counter= 0; while($counter < $n)
{
echo ' '.$num1;
$num3= $num2 + $num1;
$num1= $num2;
$num2= $num3;
$counter= $counter+1;
}
}
//for a pre defined number for Fibonacci.
$n=10; Fibonacci($n);
?>

Code Explanation:

  1. Here n is defined as equal to 10, so the logic will run till nth element e. Until we have n=10 elements in the series.
  2. First element is initialized to 0 and second element is initialized to 1, e. num1 = 0 and num2 = 1.
  3. The two elements i.e. num1 and num2 are printed as the first and second elements of the Fibonacci series.
  4. The logic we discussed will be used from here on and our iteration loop starts.
  5. According to our logic, to get num3, we need to add num1 and num2. Since currently num1 = 0 and num2 = 1, num3 comes out as 1.
  6. Now new number obtained is placed in num2 variable and num2 is saved in num1 variable. Basically simple swapping is taking place so that, now num1 is equal to ‘1’ and num2 = newly obtained num3 i.e. ‘1’.
  7. So when the next iteration happens and num3 is obtained by adding current values of num1 and num2, which, according to our PHP script, are as follows:
      • num1 = 1
      • num2 = 1
      • num3 = num1 + num2 = 1 + 1 = 2

Thus we get our next number in the Fibonacci Series.

  1. Similarly, the iteration keeps on till we achieve n = 10, size of the series that was defined in the program itself.

When the above program is executed, we get the output as follows:

Fibonacci Series PHP

2. The Recursion Way

By recursion, we mean the way where the same function is called repeatedly until a base condition is achieved or matched. At this point, recursion is stopped.

The said “function is called repeatedly” phrase points to the section in your code where we will define our logic for the Fibonacci Series.

Below is an example of generating Fibonacci Series in PHP, using If-Else conditions giving way for our recursive approach.

Here is the PHP Scripts for printing the first 15 elements for Fibonacci Series.

<?php function Fibonacci($num)
{
//If-Else IF will generate first two numbers for the series if($num == 0)
return 0;
else if($num == 1) return 1;
// This is where Recursive way comes in.
//recursive call to get the rest of the numbers in the series else
return(Fibonacci($num -1) + Fibonacci( $num -2));
}
//For a given n=15
$num =15;
for($counter = 0; $counter < $num; $counter++)
{
echo Fibonacci($counter).' ';
}
?>

Code Explanation:

This is the recursive way, which means our function that contains our logic is called again and again for generating the next element in the series until our condition for achieving a specific series size is obtained.

In Iterative approaches, the First and Second element is first initialized and printed. Here we allow a For Loop to give us our first and second elements starting with 0 and 1.

  1. We are using a For loop having a ‘counter’ variable that starts with 0. The For loop works up till the given ‘n’, size for the series.
  2. when loop starts, with the counter variable as 0, we use the recursion approach and call our defined function, Fibonacci ( ).
  3. Here code starts, with If and Else IF condition.
  4. First IF condition checks if ‘num’ variable holds value as ‘0’, if yes, then the code prints or returns ‘0’ as the element for the series.
  5. Similarly, second Else-If condition checks for the value ‘1’, if the ‘num’ variable holds ‘1’ as its value, the program returns it as it is.
  6. Next Else condition recursively calls the Fibonacci function for’ num’ values other than ‘0’ and ‘1’, continuing to reading the values from the For loop counter.

This is where our Fibonacci Logic comes into work and the next number in the sequence is obtained by adding its previous two numbers. Because this is the recursive method, we need to give a counter value to count the recursions equal to nth value, which is being handled by our For Loop.

When the above program or code is executed, the following output is displayed.

Fibonacci Series PHP

The Fibonacci Series does not only appear in mathematics or science calculations but in nature too, have you ever noticed Yellow chamomile flower head.

The Fibonacci Series if plotted on a graph, it forms a spiral called Fibonacci Spiral. It is also one of the gems given by Indian soil. It is found in Indian Mathematics as early as 200 BC in the works done by the mathematician, Pingala. Later Fibonacci introduced the sequence to European countries in his book Liber Abacci in 1200s.

The above is the detailed content of Fibonacci Series PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.