Get Fibonacci Numbers Using PHP

Tuesday, October 7, 2008 - 13:20

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
2
3
for ( $i=2; $i<=10; ++$i ) {
 $fibarray[$i] = $fibarray[$i-1] + $fibarray[$i-2];
}

This will create an array with the following values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.

1
2
3
4
5
6
7
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.

1
2
3
4
5
6
7
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.

Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

Thanks for share that code with us.

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.

Add new comment