Find Factorial in PHP

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code Examples
Recursion & loop

What you’ll learn

  • The definition of n! for n ≥ 0, including 0! = 1.
  • A recursive solution matching classic interview style, plus an iterative equivalent.
  • Large-value notes, input validation, and a small live preview.

Overview

Factorial grows faster than exponentials. A robust interview answer handles n ≥ 0, explains 0! = 1, and compares recursion with iteration.

Two programs

Recursive (5! = 120) and iterative with the same result.

Live preview

Exact integers for 0 ≤ n ≤ 20 in this widget.

Rigor

Guards for negative input and notes for very large n.

Prerequisites

Functions, if, multiplication, and optional for loops.

  • Basic PHP syntax: <?php, function, type hints, and echo.
  • Awareness that factorial values grow quickly and may exceed normal integer ranges.

What is factorial?

For an integer n ≥ 0, n! is the product of every integer from 1 through n. When n = 0, that is the empty product, defined as 1, so 0! = 1.

Factorials count permutations: n! is the number of ways to order n distinct objects. They appear in series, combinations, and probability.

5! 120
Recurrence n! = n·(n-1)!
0! 1

Formal definition

Define 0! = 1 and, for n ≥ 1, n! = n · (n-1)!. Equivalently n! = ∏k=1n k.

5!

5 × 4 × 3 × 2 × 1 = 120.

Intuition

5! 120
Expand
5·4·3·2·1
6! 720
Step
6 · 5!

Takeaway: each increment of n multiplies the previous factorial by n, which is why values explode in size.

Live preview

Exact factorial for 0 ≤ n ≤ 20 in this preview.

Try 0, 12, or 20. Larger values are not shown exactly here.

Live result
Press “Compute n!”.

Algorithm

Goal: compute n! for nonnegative n in PHP.

Base case

If n ≤ 1, return 1 (covers 0! and 1!).

Recurrence or loop

Otherwise multiply n by (n-1)!, or use a loop multiplying factors 2..n.

📜 Pseudocode

Pseudocode
function factorial(n):  // assume n >= 0
    if n <= 1:
        return 1
    return n * factorial(n - 1)
1

Recursive factorial

Classic recursive style with a small input guard for nonnegative values.

php
<?php
function factorialRecursive(int $num): int
{
    if ($num === 0 || $num === 1) {
        return 1;
    }
    return $num * factorialRecursive($num - 1);
}

$number = 5;

if ($number < 0) {
    echo "Factorial is not defined for negative integers here.\n";
} else {
    $result = factorialRecursive($number);
    echo "Factorial of {$number} is: {$result}\n";
}
?>

Explanation

Each recursive call reduces $num until the base case, then multiplies while returning back up the call stack.

2

Iterative factorial

Same numeric result for n = 5, with O(1) auxiliary space and no recursion depth concerns.

php
<?php
function factorialIterative(int $n): int
{
    $r = 1;
    for ($i = 2; $i <= $n; $i++) {
        $r *= $i;
    }
    return $r;
}

$number = 5;

if ($number < 0) {
    echo "Factorial is not defined for negative integers here.\n";
} else {
    echo "Factorial of {$number} is: " . factorialIterative($number) . "\n";
}
?>

Explanation

The loop multiplies 1 by every integer from 2 to n. For n in {0,1}, it stays 1.

Optimization and scaling

Bigger values. Use arbitrary-precision methods when exact integer factorials exceed normal ranges.

Advanced methods. Prime-based or split-recursion methods reduce large multiplication overhead, but are beyond basic interviews.

Interview: state input validation, mention growth/overflow, and compare recursion depth vs loop.

❓ FAQ

For a nonnegative integer n, n! is the product of all integers from 1 through n. By definition, 0! = 1 (empty product).
Both 0! and 1! equal 1. These cases stop the recurrence n! = n * (n-1)!.
Factorials grow very fast. With fixed-size integers, overflow happens quickly. For larger n, use arbitrary-precision techniques.
Both run O(n) multiplications. Recursion uses O(n) call stack; a loop uses O(1) extra space and avoids deep recursion issues.
Factorial is not defined for negative integers in the standard combinatorial sense. Validate n >= 0 before computing.
Computing n! with n multiplications costs O(n) time. Space is O(n) for recursion depth or O(1) for an iterative loop.

🔄 Input / output examples

Change $number in either example (within 0..20 for exact preview values).

nn!
01
11
5120
202432902008176640000

Edge cases and pitfalls

Factorial grows quickly, so always validate input and mention limits for large values.

Negative

n < 0

Not part of the standard factorial definition; reject such inputs in this tutorial.

Growth

Very large n

Values become huge quickly; you need arbitrary-precision techniques for exact large results.

Stack

Deep recursion

Large recursion depth can fail; use an iterative loop when depth is a concern.

Base case

0! = 1

Do not forget this definition; it is essential for both recursive and iterative correctness.

⏱️ Time and space complexity

VersionTimeExtra space
RecursiveO(n) multiplicationsO(n) call frames
IterativeO(n) multiplicationsO(1)

Both approaches use Θ(n) arithmetic operations for exact n!; the stack usage differs.

Summary

  • Definition: 0! = 1 and n! = n·(n-1)! for n ≥ 1.
  • Code: recursion matches the classic template; iteration saves call-stack depth.
  • Watch-outs: negatives undefined, fast growth for large n, and recursion depth limits.
Did you know?

Stirling's approximation describes how fast n! grows: asymptotically n! ∼ √(2πn) · (n/e)n. It is standard in analysis even when exact integers become very large.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful