Surprised there’s no mention of tail-recursive optimization:
function fact($n, $total=1) {
if($n < 2)
return $total;
else
return fact($n-1, $total * $n);
}
By passing a running total we can save the space and time required as well as avoiding worry about the stack size. Cheers!
https://en.wikipedia.org/wiki/Tail_call