Display Multiplication Table in PHP

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Loops

What You’ll Learn

A multiplication table for base n is the list of products n×1 through n×k. This tutorial covers the for-loop pattern, CLI input with validation, a live preview, worked PHP examples, edge cases, and complexity.

Times Table

Base × i

Print one product per row for a chosen base number.

For Loop

i = 1..k

Repeat the same formula while only the counter changes.

Fixed Base

Table of 5

Hard-code a base for a classic homework demo.

CLI Input

Validate

Read a positive integer, then print its table.

Live Preview

Any base

Try another base and see rows 1 through 10 instantly.

O(k) Cost

O(1) space

Printing k rows is linear in the row count.

Introduction

A multiplication table (times table) for a base n lists the products n×1, n×2, … up to some last multiplier. School-style programs usually stop at 10.

In PHP you fix a base, loop a counter $i from 1 to $last, and echo each row as $base x $i = product. No arrays are required for the basic version.

Why it matters?

It is a classic first loop drill: counters, multiplication, formatted output, and optional input validation in one short exercise.

Key Highlights

One Formula

Each row is $base * $i.

Countable Range

$last controls how many rows you print.

Fixed or Input

Hard-code a base or read it from STDIN.

Validate Input

Reject non-positive bases for school-style tables.

In short: choose a base, loop $i from 1 to $last, and print $base x $i = $base * $i on each line.

📝 Problem & Approach

Given a base integer and a last multiplier (often 10), print each product from 1 through that last value.

php
// base = 5, last = 10
// 5 x 1 = 5
// 5 x 2 = 10
// ...
// 5 x 10 = 50

Inputs & Outputs

ItemTypeDescription
$baseintThe number whose times table you print (usually > 0).
$lastintHighest multiplier (commonly 10 or 12).
Printed outputtextOne line per product, optionally with a header.

Minimal workflow

Pseudocode
procedure print_table(base, last):
    print header with base
    for i from 1 to last:
        print base, i, and base * i

Method comparison

MethodIdeaNotes
for loopCounter 1..lastInterview / homework default
while loopManual counterSame math; more boilerplate
Hard-coded echoesTen print linesWorks but does not scale

⚡ Quick Reference

GoalPattern
Row product$base * $i
Print a rowecho "$base x $i = " . ($base * $i) . "\n";
Loop rangefor ($i = 1; $i <= $last; $i++)
Read CLI input$raw = trim(fgets(STDIN));
Validate positiveif (!is_numeric($raw) || (int)$raw <= 0)
Custom lengthChange $last (e.g. 12)

📋 for vs while vs Hard-Coded Lines

Same table — different ways to get there.

for loop
1..last

This page — clear when the count is known

while loop
$i++; while

Same products; you manage the counter yourself

Hard-coded
10 echoes

Fine for demos; painful to change the range

Interview tip
validate input

Say what you do for 0 / negative / non-numeric

Context

When This Problem Shows Up

Reach for a times-table drill when loops and formatted output matter.

  1. First loop exercises

    Teach counters without needing arrays or recursion.

  2. CLI input practice

    Read a number, validate it, then print a table.

  3. Interview warm-ups

    Quick check of loops, formatting, and edge talk.

  4. Before nested tables

    A single-base table is the step before an m×n grid.

  5. Not for huge ranges alone

    Printing millions of rows is I/O-bound — keep demos small.

Key benefit: one visual loop problem that covers counters, multiplication, output formatting, and input checks.

🔮 Live Preview

Default base 5 matches Example 1. Change it to any reasonable integer; rows run from 1 to 10.

Runs in your browser. Very large bases may wrap awkwardly in the box; your PHP program still computes the product.

Live result
Press “Print table”.

Examples Gallery

Three complete PHP programs — fixed table for 5, CLI input with validation, and a custom 1–12 range. Click View Output to reveal sample console results.

📚 Getting Started

A reusable helper and a hard-coded base of 5.

Example 1 — Table for 5 (Fixed Base)

Print 5×1 through 5×10 with a small reusable function.

php
<?php
function printMultiplicationTable(int $base, int $last): void
{
    echo "Multiplication table for $base:\n";
    for ($i = 1; $i <= $last; $i++) {
        echo "$base x $i = " . ($base * $i) . "\n";
    }
}

$base = 5;
$last = 10;
printMultiplicationTable($base, $last);
?>

How It Works

$last controls how many rows you print — change it to 12 if you need a 1-through-12 table. The letter x in the output is just text; it is not an algebra variable.

⚡ Read From the User

Same loop; the base comes from STDIN with a positive-integer check.

Example 2 — Table for a Number You Type

Reads one integer and prints 1–10 for that base. Rejects non-positive values.

php
<?php
function printMultiplicationTable(int $base, int $last): void
{
    echo "Multiplication table for $base:\n";
    for ($i = 1; $i <= $last; $i++) {
        echo "$base x $i = " . ($base * $i) . "\n";
    }
}

echo "Enter a positive integer: ";
$raw = trim(fgets(STDIN));

if (!is_numeric($raw) || (int)$raw <= 0) {
    echo "Please enter a positive integer.\n";
    exit(1);
}

$n = (int)$raw;
printMultiplicationTable($n, 10);
?>

How It Works

fgets(STDIN) reads a line; trim removes the newline. The guard keeps the program in the usual “positive times table” style before the helper runs.

⚙️ Change the Range

Same helper — pass a different $last for 1 through 12.

Example 3 — Custom Range (1 Through 12)

Shows that row count is a parameter, not a hard-coded magic number inside the loop.

php
<?php
function printMultiplicationTable(int $base, int $last): void
{
    echo "Multiplication table for $base (1 to $last):\n";
    for ($i = 1; $i <= $last; $i++) {
        echo "$base x $i = " . ($base * $i) . "\n";
    }
}

printMultiplicationTable(7, 12);
?>

How It Works

Keeping $base and $last as parameters makes the helper reusable for homework variants and interview follow-ups. The loop body never changes — only the bounds do.

🧠 How the Algorithm Prints Rows

1

Choose base & range

Set $base (fixed or from input) and $last (often 10).

Setup
2

Optional header

Print a title line so the table is easy to read.

Label
3

Loop and multiply

For each $i from 1 to $last, print $base * $i.

Loop
=

Table complete

All requested rows are printed.

🔎 Worked Walkthrough — Base 5, First Five Rows

Trace products for $base = 5 while $i runs from 1 to 5 (the full Example 1 continues to 10).

$iExpressionPrinted product
15 * 15
25 * 210
35 * 315
45 * 420
55 * 525

Continue the same pattern through $i = 10 to finish Example 1.

Use Cases

Where a printed times table (and its loop pattern) shows up beyond the prompt.

1. Loop Teaching

Counters and repeated formulas without arrays.

Example: print table of 5.

2. CLI Practice

Read, validate, then generate output.

Example: Example 2 pattern.

3. Formatting Drills

Align columns with padded widths later.

Example: sprintf-style fields.

4. Before Nested Grids

Single-base tables lead to full m×n charts.

Example: outer base, inner multiplier.

5. Complexity Talk

State O(k) for k printed rows.

Example: last = 10 → 10 multiplies.

6. Parameter Design

Reuse one helper with different bases and ranges.

Example: Example 3 pattern.

Pro Tip: open with “for i from 1 to last, print base × i” before writing any PHP syntax.

Advantages

Why the looped times-table approach works well for beginners and interviews.

  1. 1. Tiny Mental Model

    One formula, one counter — easy to dry-run on paper.

  2. 2. Easy to Parameterize

    Change $base or $last without rewriting the loop body.

  3. 3. Natural CLI Follow-Up

    Add input and validation without changing the core idea.

  4. 4. Clear Complexity

    O(k) time for k rows — easy to state in an interview.

Pro Tip: extract printMultiplicationTable($base, $last) early so fixed and interactive demos share one implementation.

Usage Tips

Small habits that keep times-table solutions interview-ready.

  1. 1. Parameterize $last

    Avoid magic 10 inside the loop when the prompt may ask for 12.

  2. 2. Validate CLI Input

    Check numeric and positive before printing.

  3. 3. Prefer Inclusive Bounds

    Use $i <= $last so the final multiplier is included.

  4. 4. Keep Output Readable

    A short header makes sample output easy to grade.

  5. 5. State O(k) / O(1)

    One multiply and print per row.

Pro Tip: dry-run 5 x 1 through 5 x 5 aloud — if products match, your loop bounds are almost certainly correct.

Common Pitfalls

Mistakes that commonly break multiplication-table solutions.

  1. 1. Off-by-One on $last

    Using $i < $last skips the final row.

    → Prefer $i <= $last for inclusive ranges.

  2. 2. Skipping Input Validation

    Printing a table for empty or non-numeric input.

    → Check is_numeric and positivity first.

  3. 3. Hard-Coding Ten Echoes

    Copy-pasted lines instead of a loop.

    → Use for so changing the range is one edit.

  4. 4. Starting at Zero

    Including 0 when the assignment expects 1–10.

    → Confirm the prompt’s first multiplier.

  5. 5. Confusing x With Multiplication

    Thinking the printed x is an operator.

    → Compute with *; print x only as text.

Edge Cases

Handle these before calling the table printer done.

Bad input

Invalid CLI input

Show a friendly message instead of printing an invalid table.

Zero / negative

Non-positive base

Decide whether to reject (as here) or allow — classic tables usually use a positive base.

last = 1

Single row

Loop still works; output is just base x 1 = base.

Large base

Wide products

PHP ints are usually fine for demos; formatting may need wider columns.

last < 1

Empty range

Validate $last if callers can pass zero or negatives.

Whitespace

Padded CLI lines

trim input before casting to int.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Repeated addition. n×k is n added to itself k times — the loop just prints the closed form.
  • Commutative products. 5×7 equals 7×5 — useful if you later print a full grid.
  • I/O dominates. For small k, printing usually costs more wall time than the multiplications.
  • While is fine. Interviewers care that you understand the counter, not that you insist on for.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Dry-run base 5

  • Trace products through i = 10
  • Expect final line 5 x 10 = 50

2. CLI validation

  • Reject 0, negatives, and letters
  • Accept a positive integer like 4

3. Print 1 through 12

  • Reuse Example 3’s signature
  • Only change $last

4. While-loop rewrite

  • Same output as Example 1
  • Manage $i manually

Notes

  • Core loop: for each $i, print $base * $i.
  • Cost: linear in the number of rows printed.
  • Formatting: you can align columns with fixed widths later for tidier grids.
  • Stretch: read $base (and maybe $last) from the user with validation.

Quick Takeaway: loop $i from 1 to $last, print $base * $i each time, and validate interactive input.

⏱️ Time and Space Complexity

TaskTimeExtra space
Print $last rowsO(last)O(1)
CLI parse + validateO(1)O(1)

For interview-sized tables, the loop cost is tiny; clarity matters more than micro-optimizations.

Wrap Up

🎉 Conclusion

A multiplication table is a counted loop: fix a base, walk $i from 1 to $last, and print each product. Parameterize the helper so fixed demos, CLI input, and custom ranges share one implementation.

Practice the three examples above, then continue to checking natural numbers.

for i = 1..last: print base × i — validate interactive bases before you loop.

💡 Best Practices

✅ Do

  • Use a for loop with inclusive $last
  • Parameterize base and row count
  • Validate CLI input when reading from STDIN
  • Print a short header for readability
  • State O(k) time for k rows

❌ Don’t

  • Hard-code ten separate echo lines
  • Skip validation on interactive input
  • Use < when you meant <=
  • Treat printed x as an operator
  • Ignore what the prompt says about 0 / negatives

Key Takeaways

Knowledge Unlocked

Five things to remember about multiplication tables

Print times tables the interview-friendly way.

5
Core concepts
02

Loop

i = 1..last

Code
5 03

Fixed

Hard-coded base

Demo
! 04

Input

Validate first

CLI
O 05

Cost

O(k) / O(1)

Analysis

❓ Frequently Asked Questions

It is a neat list of answers for "n times 1," "n times 2," and so on — usually up to 10 in homework-style programs. Each row is one multiply.
The pattern repeats: same formula (base times counter), only the counter changes. A loop writes every row without copying the echo line ten times.
School tables often go 1–10. You can change the upper limit to 12 or any positive integer; it is just a design choice.
Yes. A for loop is convenient when you know how many steps you want; a while loop can do the same with a counter you update by hand.
Multiplication still works in PHP, but a times table for non-positive bases is unusual. Example 2 checks for positive input; you can tighten rules for your assignment.
Printing k rows costs O(k) time and O(1) extra space besides the output lines.
Hard-coded bases are fine for demos. Interviews and assignments often ask for CLI input plus a simple validation check.
Pass a different $last to the helper — the loop body stays the same.

Did you Know? 🔊

A multiplication table for a number n is just the list of products n×1, n×2, …. Each line is one multiplication — what you practiced as “times tables” in school — now printed by a loop instead of by hand.

Continue to Natural Number

Learn how to check whether a number is a natural number (positive integer) in PHP.

Natural number tutorial →

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