# Get Fibonacci Numbers Using PHP

7th October 2008 - 4 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 = \$fibarray + \$fibarray;``

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
 => 1
 => 1
 => 2
 => 3
 => 5
 => 8
 => 13
 => 21
 => 34
 => 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.