PHP Factorial of a Number Program

Beginner
6 min read
Updated: Oct 2026
2 programs
Live preview

What Is the Factorial of a Number?

The factorial of a nonnegative integer n, written n!, is the product of every integer from 1 through n. By definition, 0! = 1.

Remember
n! = 1 × 2 × 3 × … × n   (for n ≥ 1)
0! = 1

Example: 5!
  5 × 4 × 3 × 2 × 1 = 120

Recurrence:
  n! = n × (n − 1)!
  with base case 0! = 1! = 1
nExpansionn!
0(empty product)1
111
55 × 4 × 3 × 2 × 1120
66 × 5!720

How to Find Factorial in PHP

Four clear steps — then pick a loop or recursion.

  1. Reject negative inputs (factorial is not defined for them).
  2. Treat 0 and 1 as the base case: return 1.
  3. Multiply all integers from 2 through n (loop), or use n × (n − 1)! (recursion).
  4. On 64-bit PHP, stay within 20! for exact ints — use GMP for larger exact values.
MethodIdeaTimeBest for
Iterative loopMultiply 2..n into a running productO(n)Production, larger n, interviews
Recursionn × Factorial(n − 1) with base ≤ 1O(n)Showing the recurrence clearly

Pseudocode

Pseudocode
function Factorial(n):
    if n < 0:
        error "not defined"
    if n <= 1:
        return 1

    result = 1
    for i from 2 to n:
        result = result * i

    return result

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
DefinitionProduct of 1..n; 0! = 1
Base cases0 and 1 both return 1
Recurrencen! = n × (n − 1)!
Safe int rangeExact through 20! on 64-bit PHP
NegativesReject — undefined for integers
Classic check5! → 120
Large ngmp_fact($n) when GMP is available

Live Preview

Enter a nonnegative integer (0–20) to see the product chain and n!.

Whole numbers from 0 to 20 (exact in this preview). Tap a chip or type a value.

Result
n = 5
Chain: 1 × 2 × 3 × 4 × 5
5! = 120

Worked Walkthrough — n = 5

Start at 1 and multiply each next integer until you reach 5.

Calculation
result = 1

i = 2 → result = 1 × 2 = 2
i = 3 → result = 2 × 3 = 6
i = 4 → result = 6 × 4 = 24
i = 5 → result = 24 × 5 = 120

Stop (i reached n)
5! = 120

Recursive view:
  5! = 5 × 4!
  4! = 4 × 3!
  3! = 3 × 2!
  2! = 2 × 1!
  1! = 1
  → 120

PHP Programs

Start with the iterative loop for interviews and real code. Use recursion when you want to show the recurrence clearly.

Example 1 — Iterative Loop

Multiply integers from 2 to n into a running product. No recursion-depth risk.

php
<?php
function factorial($n) {
    if ($n < 0) {
        throw new InvalidArgumentException("Factorial is not defined for negatives.");
    }

    $result = 1;
    for ($i = 2; $i <= $n; $i++) {
        $result *= $i;
    }
    return $result;
}

$number = 5;
echo $number . "! = " . factorial($number) . "\n";
?>

How It Works

  1. Reject $n < 0 — integer factorial is undefined there.
  2. Start with $result = 1 (covers both 0! and 1!).
  3. Loop $i from 2 to $n and multiply into $result.
  4. For $n = 5: 1 → 2 → 6 → 24 → 120.
  5. Extra space is O(1) — prefer this style in real code.

Example 2 — Recursion

Direct translation of n! = n × (n − 1)! with base cases 0 and 1.

php
<?php
function factorial($n) {
    if ($n < 0) {
        throw new InvalidArgumentException("Factorial is not defined for negatives.");
    }
    if ($n <= 1) {
        return 1;
    }
    return $n * factorial($n - 1);
}

echo factorial(5) . "\n"; // 120
echo factorial(0) . "\n"; // 1
?>

How It Works

  1. Validate $n >= 0 first.
  2. Base case: if $n <= 1, return 1 (stops the recursion).
  3. Otherwise return $n * factorial($n - 1).
  4. For 5: calls unwind as 5×4×3×2×1 = 120.
  5. Uses O(n) stack frames — fine for interviews; use a loop for large $n.

Edge Cases & Pitfalls

Check these before calling the solution done.

0! / 1!

Both equal 1

The loop body never runs; recursion hits the base case immediately.

Negatives

Reject early

Do not silently return a wrong product — validate $n >= 0.

Overflow

Exact ints to 20!

Beyond that, PHP may promote to float and lose precision. Use GMP for exact large values.

Recursion

Stack / nesting limit

Deep recursion can hit xdebug.max_nesting_level or exhaust the call stack — prefer a loop.

Time and Space Complexity

ProgramTimeExtra space
Iterative loopO(n)O(1)
RecursionO(n)O(n) call stack

Both need about n multiplications. Space differs: the loop keeps one product; recursion keeps one frame per level.

Key Takeaways

  • Definition: n! multiplies 1..n; 0! = 1.
  • Loop: safest default — O(1) extra space.
  • Recursion: n × (n − 1)! with base n ≤ 1.
  • Test set: 0! → 1; 5! → 120; 6! → 720; reject negatives.

One line: multiply 1 through n (return 1 for 0 and 1) — loop preferred, recursion for teaching.

Frequently Asked Questions

For a nonnegative integer n, n! is the product of all integers from 1 through n. By definition, 0! = 1.
It is the empty product, and it makes the recurrence n! = n × (n − 1)! work when n = 1.
Both need O(n) multiplications. Recursion uses O(n) call-stack space; a loop uses O(1) extra space and is safer for larger n.
On 64-bit PHP, 20! fits in an integer. Beyond that, values may become floats and lose precision — use GMP (gmp_fact) for exact large factorials.
Standard integer factorial is not defined for negatives. Validate n >= 0 before computing.
No standard factorial function. Write a loop or recursion in interviews; mention gmp_fact when the GMP extension is available.

Next: Fibonacci Series

Generate the Fibonacci sequence with a loop or recursion.

Fibonacci series tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

12 people found this page helpful