Progressive Reverse-Build Number Pattern in PHP

Beginner
⏱️ 7 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Modulo + Division

What You’ll Learn

This pattern builds the reverse of a number step by step, printing after each digit append. Starting from $num = 86523: 3, 32, 325, 3256, 32568. Use $num % 10 to extract digits and intdiv($num, 10) to shrink the source. This tutorial covers the loop logic, live preview, worked PHP examples, edge cases, and O(d) complexity.

Extract Digit

$num % 10

Modulo gets the last digit: 86523 % 10 → 3.

Append to Reverse

$reverse * 10 + digit

Shift reverse left and add the digit: 0 → 3 → 32 → 325.

Print Reverse

echo $reverse

Each iteration prints the growing reverse value.

After Program 60

% 10 + intdiv

Natural next step — Program 60 printed $num; this builds $reverse.

Live Preview

Any integer

Enter a starting number and see each progressive reverse line instantly.

O(d)

Complexity

One iteration per digit — linear in the number of digits.

Introduction

A progressive reverse-build pattern appends the last digit of $num to a running $reverse value and prints it each step.

In PHP: while ($num != 0), update $reverse = $reverse * 10 + ($num % 10), echo $reverse, then $num = intdiv($num, 10).

Why it matters?

Pairing % 10 and / 10 is the core technique for reversing numbers, counting digits, and checking palindromes — the natural follow-up to Program 60.

Key Highlights

Modulo %10

$num % 10 extracts the last digit each step.

Build reverse

$reverse * 10 + digit appends to the right.

vs Program 60

Program 60 printed $num; this prints growing $reverse.

O(d) time

Runs once per digit — very efficient.

In short: while $num != 0, append $num % 10 to $reverse, echo $reverse, then $num = intdiv($num, 10).

📝 Problem & Approach

Given $num = 86523, build and echo $reverse after each digit is appended: 3, 32, 325, 3256, 32568.

PHP
$num = 86523;
$reverse = 0;
while ($num != 0) {
    $reverse = $reverse * 10 + ($num % 10);
    echo $reverse . PHP_EOL;
    $num = intdiv($num, 10);
}

Inputs & Outputs

ItemTypeDescription
$numintStarting positive integer — loop runs while $num != 0.
$reverseintRunning reverse built with $reverse * 10 + ($num % 10).
Printed outputtextOne line per iteration — growing reverse: 3, 32, 325, 3256, 32568.

Minimal workflow

Pseudocode
$reverse = 0
while $num != 0:
    $reverse = $reverse * 10 + ($num % 10)
    echo $reverse
    $num = intdiv($num, 10)

Approach comparison

ApproachIdeaBest for
While + modulo$reverse * 10 + $num % 10Classic reverse build — Example 1
fgets(STDIN) inputfgets(STDIN) for $numUser-chosen starting number
string accumulator$reverse as string for large inputsOverflow-safe variant — Example 3
Program 60 contrastEcho $num then intdivRemoves digits instead of building reverse

⚡ Quick Reference

GoalPattern
Init accumulator$reverse = 0;
Loop conditionwhile ($num != 0)
Extract last digit$num % 10
Append to reverse$reverse = $reverse * 10 + ($num % 10);
Print progressive lineecho $reverse . PHP_EOL;
Shrink num$num = intdiv($num, 10);

📋 Modulo Build vs Echo num vs String

Three teaching angles — progressive reverse build (this program), digit removal (Program 60), and overflow-safe string $reverse.

Modulo + build
$reverse = $reverse * 10 + $num % 10

Core pattern for Examples 1 and 2.

Program 60
echo $num; $num = intdiv($num, 10)

Echoes shrinking $num instead of growing $reverse.

string $reverse
$reverse = "";

Safer for very large inputs — Example 3.

Learning tip
build, echo, then intdiv

Update $reverse and echo before dividing $num.

Context

When This Pattern Shows Up

Use progressive reverse-build when teaching modulo, digit extraction, and partial reverse snapshots in one while loop.

  1. After Program 60

    Natural next step once students can divide by 10 — now combine with % 10.

  2. Reverse-number drills

    Print intermediate reverses before the classic single-line reverse program.

  3. Console I/O practice

    Pair with fgets(STDIN) — see Example 2.

  4. Gateway to spirals

    Continue to Program 62 (Perfect Square Spiral) after mastering digit loops.

  5. Not a UI layout tool

    Console teaching pattern — builds algorithmic thinking, not screen layouts.

Key benefit: one loop that connects modulo, multiply-by-10, and progressive output.

🔮 Live Preview

Enter a starting number and see each progressive reverse-build line.

Try 86523, 12345, or 987654.

Live result
Press "Draw pattern".

Examples Gallery

Three complete PHP programs — fixed $num = 86523, fgets(STDIN) input, and a string overflow-safe variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five progressive reverse lines from 86523: 3, 32, 325, 3256, 32568.

Example 1 — Fixed $num = 86523

Build $reverse digit by digit and print after each append.

PHP
<?php
$num = 86523;
$reverse = 0;

while ($num != 0) {
    $reverse = $reverse * 10 + ($num % 10);
    echo $reverse . PHP_EOL;
    $num = intdiv($num, 10);
}

How It Works

First iteration takes digit 3, sets $reverse to 3, then $num becomes 8652. Each step appends the next last digit until $num is 0.

📈 Practical Variant

Read the starting number with fgets(STDIN).

Example 2 — User Input

Same reverse-build loop; starting number comes from user input.

PHP
<?php
echo "Enter a number: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input)) {
    echo "Invalid input." . PHP_EOL;
    exit(1);
}
$num = (int) $input;
$reverse = 0;

while ($num != 0) {
    $reverse = $reverse * 10 + ($num % 10);
    echo $reverse . PHP_EOL;
    $num = intdiv($num, 10);
}

How It Works

Same progressive reverse build as Example 1; only the source of $num changes.

⚡ Overflow-Safe Variant

Use a string for $reverse when inputs may be large.

Example 3 — String Accumulator

Identical visual result building $reverse with string concatenation — no integer overflow.

PHP
<?php
$num = 86523;
$reverse = "";

while ($num != 0) {
    $reverse .= (string) ($num % 10);
    echo $reverse . PHP_EOL;
    $num = intdiv($num, 10);
}

How It Works

String concatenation grows without integer overflow — same output for classroom-sized inputs like 86523.

🧠 How Progressive Reverse-Build Works

1

Init $reverse = 0

$reverse = 0; and $num = 86523; before the loop.

Setup
2

Extract digit with %10

$num % 10 reads the last digit (3, then 2, then 5, …).

Modulo
3

Append $reverse * 10 + digit

$reverse = $reverse * 10 + ($num % 10); grows the reverse on the right.

Build
4

Echo reverse

echo $reverse . PHP_EOL; shows 3, 32, 325, 3256, 32568.

Print
5

Divide by 10

$num = intdiv($num, 10); removes the processed digit and moves to the next.

Divide
=

Progressive reverse complete

Exactly d lines for d digits — O(d) time, O(1) extra space.

🔎 Worked Walkthrough — $num = 86523

Trace each loop iteration: extract digit, update reverse, print, then divide.

Stepnumdigitreverse printed$num after intdiv
186523338652
28652232865
3865532586
486632568
588325680 (loop ends)

The loop stops when $num becomes zero after the fifth division.

Use Cases

Where progressive reverse-build and digit-manipulation loops show up in PHP courses.

1. Full Number Reverse

Same loop structure prints only the final reverse instead of each step.

Example: move echo outside the loop to print only the final reverse.

2. Palindrome Check

Combine % 10 and / 10 to build a reversed half for comparison.

Example: compare digits from both ends using modulo and division.

3. Count Digits

Same shrink loop counts how many digits a number has.

Example: increment a counter each iteration until num is 0.

4. Program 60 Contrast

Program 60 printed shrinking $num; this prints growing $reverse.

Example: compare both outputs side by side from the same starting value.

5. O(d) Complexity

Linear in digit count — much faster than grid patterns for large numbers.

Example: 86523 has 5 digits → 5 loop iterations.

6. Input Validation

Pair with fgets(STDIN) and reject zero or negative input if required.

Example: use is_numeric($input) before reading input.

Pro Tip: always update and echo $reverse before dividing $num — dividing first skips the current digit.

Advantages

Why progressive reverse-build belongs in beginner PHP courses.

  1. 1. One Simple Loop

    No nested loops — natural follow-up to Program 60’s digit-removal loop.

  2. 2. Teaches Modulo + Build

    $num % 10 and $reverse * 10 + digit are core reverse tools.

  3. 3. Easy to Extend

    Try fgets(STDIN) input, string variant, or continue to Program 62.

  4. 4. O(1) Extra Memory

    Only one integer variable changes — no arrays needed.

Pro Tip: trace 86523 on paper — five lines, five digit appends, then stop.

Usage Tips

Small habits that keep reverse-build code correct.

  1. 1. Append Before Divide

    Always update and echo $reverse . PHP_EOL first, then $num = intdiv($num, 10).

  2. 2. Use Integer Division

    Keep $num as int — floating-point division breaks digit removal.

  3. 3. Loop Until Zero

    while ($num != 0) stops when the last digit has been appended, printed, and divided away.

  4. 4. Handle Zero Input

    If $num starts at 0, the loop never runs — validate or show a message.

  5. 5. Prefer intdiv

    Prefer intdiv($num, 10) — bare $num /= 10 yields a float in PHP.

Pro Tip: if the first line is wrong, you divided before appending the digit to $reverse.

Common Pitfalls

Mistakes that commonly break progressive reverse-build patterns.

  1. 1. Dividing Before Updating reverse

    First line shows 32 instead of 3 — you divided before appending the current digit.

    → Update $reverse and print first, then divide.

  2. 2. Infinite Loop

    Forgetting $num = intdiv($num, 10) leaves $num unchanged forever.

    → Always update $num inside the loop body.

  3. 3. Floating-Point Division

    Using float division ($num / 10) can introduce precision issues on large values.

    → Use intdiv (not float division) for clean digit removal.

  4. 4. Unchecked User Input

    Letters or empty input leave $num uninitialized.

    → Call is_numeric($input) before casting to int.

  5. 5. Starting num at 0

    while ($num != 0) never executes — no output at all.

    → Validate input or show a message when num is 0.

Edge Cases

Check these inputs before calling the solution done.

num = 0

Zero input

Loop never runs — print nothing or show a message.

Single digit

num = 8

Output is one line: 8 — then num becomes 0.

Trailing zero

num = 120

Prints 120 then 12 then 1 — zero drops immediately.

Negative

Trailing zeros in input

Use Math.abs(num) first for clean positive output.

Bad input

Non-numeric fgets(STDIN) input

Call is_numeric($input) before reading $num.

Large num

Large values

Use a string $reverse if the integer may overflow — see Example 3.

🎯 Practice Problems

Try these variations to lock in progressive reverse-build.

1. Change starting number

  • Try 12345, 999, or 120
  • Count how many lines print

2. Print only final reverse

  • After the loop, echo $reverse once without intermediate lines
  • Compare with the progressive print version

3. String variant

  • Rewrite with string $reverse — Example 3
  • Confirm output matches the int version for 86523

4. Next in series

  • Continue with Program 62
  • Perfect Square Spiral after digit-loop mastery

Notes

  • Digit count. Loop runs once per digit — O(d) time for d digits.
  • % 10 extracts the last digit; / 10 removes it — pair them in every reverse-build loop.
  • Validate $num != 0 for interactive programs; zero input prints nothing.
  • Compare with Program 60 (prints shrinking $num) — this pattern prints growing $reverse.

Quick Takeaway: append $num % 10 to $reverse, echo $reverse, then $num = intdiv($num, 10), repeat while $num != 0.

⏱️ Time and Space Complexity

ProgramTimeExtra space
While loop (Examples 1–2)O(d)O(1)
string variant (Example 3)O(d)O(1)
Wrap Up

🎉 Conclusion

The progressive reverse-build pattern is a compact while-loop lesson: extract the last digit, append to $reverse, print, divide by 10, repeat until zero. Master the fixed-$num version, then try fgets(STDIN) input and the string variant in Example 3.

Practice the three examples above, then continue to Program 62 for the Perfect Square Spiral pattern.

Build then echo — loop while $num != 0 — O(d) time for d digits.

💡 Best Practices

✅ Do

  • Update and echo $reverse before $num = intdiv($num, 10)
  • Use while ($num != 0) as the loop condition
  • Validate non-zero input for interactive programs
  • Call is_numeric($input) before using fgets(STDIN) input
  • State O(d) time when asked about complexity

❌ Don’t

  • Divide before updating $reverse
  • Forget to update $num inside the loop
  • Use floating-point types for reverse build
  • Ignore zero input in user-facing demos
  • Skip the single-digit edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about progressive reverse-build

One while loop, modulo append, O(d) time.

5
Core concepts
02

While loop

$num != 0

Code
/ 03

Modulo

$num % 10

Code
04

Echoes each step

d lines for d digits

Edge
O 05

Complexity

O(d) time

Analysis

❓ Frequently Asked Questions

Because 3 is the last digit of 86523. The program takes $num % 10 first and appends it to $reverse.
Each step appends the next last digit to $reverse: 3, then 2 → 32, then 5 → 325, then 6 → 3256.
Once all digits of 86523 are processed, $reverse becomes 32568 and $num becomes 0, ending the loop.
Related — you build the reverse but print it after every step rather than only the final reverse.
Trailing zeros become leading zeros in the reverse, but leading zeros are not shown in integer printing.
Yes. Use fgets(STDIN) with is_numeric() and the same loop — see Example 2.
O(d) where d is the number of digits — one loop iteration per digit.
Use trim(fgets(STDIN)) and is_numeric($input) before casting to int.
Build $reverse as a string with concatenation — see Example 3.

Did you Know? 🔊

Each step appends the last digit of $num to $reverse with $reverse = $reverse * 10 + ($num % 10), then shrinks $num with intdiv($num, 10). From 86523: 3, 32, 325, 3256, 32568O(d) time.

Continue to Program 62

Move on to the Perfect Square Spiral pattern in the PHP number-pattern series.

Program 62 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.

12 people found this page helpful