Calculate Fibonacci sequence using recursion in PHP

Description

The following code shows how to calculate Fibonacci sequence using recursion.

Example


<!DOCTYPE html>//w w w.j  a v a 2  s. c o m
<html>
  <body>
    <h2>Fibonacci sequence using recursion</h2>
    <table>
      <tr>
        <th>Sequence #</th>
        <th>Value</th>
      </tr>
        <?php
        
        $iterations = 10;
        
        function fibonacci( $n ) {
          if ( ( $n == 0 ) || ( $n == 1 ) ) return $n;
          return fibonacci( $n-2 ) + fibonacci( $n-1 );
        }
        
        for ( $i=0; $i <= $iterations; $i++ )
        {
        ?>
              <tr<?php if ( $i % 2 != 0 ) echo ' class="alt"' ?>>
                <td>F<sub><?php echo $i?></sub></td>
                <td><?php echo fibonacci( $i )?></td>
              </tr>
        <?php
        }
        ?>
    </table>
  </body>
</html>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Development »




Environment
Error
Hash
Include
Locale
Math
Network
Output
Reflection
PHP Regular Expressions