bhylu.com

Advertisements

PHP Recursion

A recursive function solves a problem through smaller calls to itself. Explain both its stopping rule and why each call approaches that rule.

How it works

Recursion is appropriate for some nested structures, but a simple loop may be easier for a numeric total. This teaching factorial uses a deliberately small non-negative range so integer overflow and stack growth do not become hidden parts of the contract. A production traversal also needs a policy for depth and, where applicable, cycles. Do not assume a recursive definition automatically makes an implementation efficient.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l recursion.php
php recursion.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · recursion.php

<?php
declare(strict_types=1);

function factorial(int $n): int {
    if ($n < 0 || $n > 10) throw new InvalidArgumentException("Use 0 through 10");
    return $n <= 1 ? 1 : $n * factorial($n - 1);
}
echo factorial(5), "\n";
echo factorial(0), "\n";

Expected result

120
1

Five expands into smaller calls until one returns the base value. Zero also uses that base definition. The input bound documents the small domain this example promises rather than presenting arbitrary-size arithmetic as supported. A loop can calculate the same result while avoiding recursive call frames.

Check the official PHP manual for detailed version and API contracts.