Calculate factorials using recursion in PHP
Description
The following code shows how to calculate factorials using recursion.
Example
// w w w . j av a 2s.co m
<!DOCTYPE html>
<html>
<body>
<h2>Calculating factorials using recursion</h2>
<table cellspacing="0" border="0" style="width: 20em; border: 1px solid #666;">
<tr>
<th>Integer</th>
<th>Factorial</th>
</tr>
<?php
$iterations = 10;
function factorial( $n ) {
if ( $n == 0 ) return 1;
return factorial( $n-1 ) * $n;
}
for ( $i=0; $i <= $iterations; $i++ )
{
?>
<tr<?php if ( $i % 2 != 0 ) echo ' class="alt"' ?>>
<td><?php echo $i?></td>
<td><?php echo factorial( $i )?></td>
</tr>
<?php
}
?>
</table>
</body>
</html>
The code above generates the following result.