Get Fibonacci Numbers Using PHP

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.

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

This will create an array with the following values.

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

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

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

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

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

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

Comments

Thanks for share that code with us.
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.
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
12 + 6 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.