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[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.