Get Fibonacci Numbers Using PHP

7th October 2008 - 2 minutes read time

Fibonacci numbers not only have a few uses, but are also quite a nice little number sequence in themselves.

The sequence starts at 0, the next number is 1, and every number after that is the sum of the last two numbers. So the third number is 1, and the second number is 2.

To create this number sequence in PHP we need to create the first two items in the array. As we know that these are 0 and 1 we can create the array like this.

$fibarray = array(0, 1);

To create the third number we just add the first two numbers together.

$fibarray[2] = $fibarray[0] + $fibarray[1];

This can be continued for as much as we want if we add it to a loop.

  1. for ( $i=2; $i<=10; ++$i ) {
  2. $fibarray[$i] = $fibarray[$i-1] + $fibarray[$i-2];
  3. }

This will create an array with the following values.

  1. Array
  2. (
  3. [0] => 0
  4. [1] => 1
  5. [2] => 1
  6. [3] => 2
  7. [4] => 3
  8. [5] => 5
  9. [6] => 8
  10. [7] => 13
  11. [8] => 21
  12. [9] => 34
  13. [10] => 55
  14. )

Following on from this we can get a Fibonacci sequence to any position we want by using the following function.

  1. function fibonacciSequence($pos){
  2. $fibarray = array(0, 1);
  3. for ( $i=2; $i<=$pos; ++$i ) {
  4. $fibarray[$i] = $fibarray[$i-1] + $fibarray[$i-2];
  5. }
  6. return $fibarray;
  7. }

We can also create a very similar function that will only return a number at a particular position.

  1. function fibonacciSequence($pos){
  2. $fibarray = array(0, 1);
  3. for ( $i=2; $i<=$pos; ++$i ) {
  4. $fibarray[$i] = $fibarray[$i-1] + $fibarray[$i-2];
  5. }
  6. return $fibarray[$pos];
  7. }

For example, if we pass this function the number 56, the result would be 225,851,433,717.

Comments

Permalink
Thanks for share that code with us.

Sarah Jay (Sun, 09/18/2016 - 21:50)

Permalink
Hi Philip, please can u send the complete program using your mention above function I have tried but can't get the output. the even error also not displaying. so please can send me the complete program.

Yogesh sonar (Wed, 04/12/2017 - 14:17)

Add new comment

The content of this field is kept private and will not be shown publicly.