0 points

PHP Recursive Functions: How to Write Them, and Why They're Useful


dashboard

Wed Dec 02 2020 05:07:07 GMT+0000 (UTC)

Posted by @mvieira

<?php

function factorial( $n ) {

  // Base case
  if ( $n == 0 ) {
    echo "Base case: $n = 0. Returning 1...<br>";
    return 1;
  }

  // Recursion
  echo "$n = $n: Computing $n * factorial( " . ($n-1) . " )...<br>";
  $result = ( $n * factorial( $n-1 ) );
  echo "Result of $n * factorial( " . ($n-1) . " ) = $result. Returning $result...<br>";
  return $result;
}

echo "The factorial of 5 is: " . factorial( 5 );

?>
content_copy Copy

https://www.elated.com/php-recursive-functions/