Remove-Last-Digit Number Pattern in PHP

Beginner
⏱️ 7 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
While Loop /10

What You’ll Learn

This pattern prints a number, then repeatedly removes the last digit with integer division by 10. Starting from 86523: 86523, 8652, 865, 86, 8. A single while loop handles it — no nested loops needed. This tutorial covers the loop logic, live preview, worked PHP examples, edge cases, and O(d) complexity.

Print First

echo $num

Each iteration prints the current value before shrinking it.

Divide by 10

intdiv($num, 10)

Integer division drops the last digit: 86523 → 8652.

While Loop

$num != 0

Loop runs once per digit until the number becomes zero.

After Grid Patterns

Program 59

Natural break from nested loops — one variable, one while loop.

Live Preview

Any integer

Enter a starting number and see each digit-removal line instantly.

O(d)

Complexity

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

Introduction

A remove-last-digit pattern prints a number line by line, dropping the rightmost digit each time using intdiv($num, 10).

In PHP: while ($num != 0), echo $num, then $num = intdiv($num, 10) until the value reaches zero.

Why it matters?

Integer division by 10 is the foundation for digit counting, reversing numbers, and palindrome checks — a natural step after grid patterns in Program 59.

Key Highlights

One loop

No nested loops — a single while suffices.

/ 10 trick

Integer division removes the last digit each step.

vs Program 61

Program 61 builds the reverse progressively with % 10.

O(d) time

Runs once per digit — very efficient.

In short: while $num != 0, echo $num, then set $num = intdiv($num, 10).

📝 Problem & Approach

Given starting number $num = 86523, print each value as you remove the last digit until the number becomes zero.

PHP
// $num = 86523 (conceptual output)
// 86523
// 8652
// 865
// 86
// 8

Inputs & Outputs

ItemTypeDescription
$numintStarting positive integer — must be non-zero for the loop to run.
Loop conditionbooleanwhile ($num != 0) — stops when division reaches zero.
Printed outputtextOne line per iteration — full number, then number minus last digit, and so on.

Minimal workflow

Pseudocode
while $num != 0:
    echo $num
    $num = intdiv($num, 10)

Approach comparison

ApproachIdeaBest for
While + divisionintdiv($num, 10) each iterationClassic digit-removal — Example 1
fgets(STDIN) inputfgets(STDIN) for $numUser-chosen starting number
String substrsubstr($s, 0, $len)String practice — Example 3
floor alternative(int) floor($num / 10)Same as intdiv for non-negative $num

⚡ Quick Reference

GoalPattern
Set starting number$num = 86523;
Loop conditionwhile ($num != 0)
Print current valueecho $num . PHP_EOL;
Remove last digit$num = intdiv($num, 10); or $num = intdiv($num, 10);
Handle negatives$num = abs($num); before the loop
Program 61 contrastProgram 61 uses % 10 to build reverse progressively

📋 Division vs String vs Modulo

Three ways to work with digits — this pattern uses division; Program 61 uses modulo.

Division /10
$num = intdiv($num, 10)

Removes last digit — used in Examples 1 and 2.

Modulo %10
digit = num % 10

Extracts last digit — used in Program 61 reverse build.

String slice
substr($s, 0, $len)

Same visual output without arithmetic — Example 3.

Learning tip
print then divide

Always print before dividing — otherwise you skip the first value.

Context

When This Pattern Shows Up

Reach for this pattern when teaching while loops, integer division, and digit manipulation without nested loops.

  1. After grid patterns

    Natural break from nested loops in Program 59 — one variable, one while loop.

  2. While-loop practice

    Simple loop condition with a clear stopping point when $num reaches zero.

  3. Console I/O practice

    Read starting number with fgets(STDIN) — see Example 2.

  4. Gateway to variants

    Compare with Program 61 (reverse build with % 10), then continue the digit series.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in while loops, integer division, and O(d) digit thinking.

🔮 Live Preview

Enter a starting number and see each digit-removal line in the browser.

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-substr variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five lines from 86523 down to 8 using a while loop.

Example 1 — Fixed $num = 86523

Print the current value, then divide by 10 until the number becomes zero.

PHP
<?php
$num = 86523;

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

How It Works

First iteration prints 86523, then $num becomes 8652. Each step removes one digit until $num is 0 and the loop exits.

📈 Practical Variant

Read the starting number with fgets(STDIN).

Example 2 — User Input

Same while-loop logic; 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;

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

How It Works

Same digit-removal loop as Example 1; only the source of $num changes.

⚡ String Variant

Same output using substr instead of division.

Example 3 — String Substr Approach

Convert to string and print progressively shorter prefixes.

PHP
<?php
$num = 86523;
$s = (string) $num;

for ($len = strlen($s); $len >= 1; $len--) {
    echo substr($s, 0, $len) . PHP_EOL;
}

How It Works

substr($s, 0, $len) prints prefixes of decreasing length — same visual result without / 10.

🧠 How the Algorithm Removes Digits

1

Set starting number

$num = 86523; — the value printed on the first line.

Setup
2

Loop while $num != 0

while ($num != 0) runs once per digit until division reaches zero.

Loop
3

Print current value

echo $num . PHP_EOL outputs the current line before shrinking.

Print
4

Divide by 10

$num = intdiv($num, 10) drops the last digit: 86523 → 8652 → 865 → 86 → 8.

Divide
=

Digit-removal sequence complete

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

🔎 Worked Walkthrough — $num = 86523

Trace each loop iteration: print, then divide by 10.

StepPrintAfter intdiv($num, 10)
1865238652
28652865
386586
4868
580 (loop ends)

Zero is never printed because the loop condition is checked before the next iteration.

Use Cases

Where integer division by 10 shows up beyond this homework pattern.

1. Count Digits

Same /10 loop counts how many digits a number has.

Example: loop until num=0 and count iterations.

2. Reverse a Number

Combine % 10 and / 10 — see Program 61.

Example: extract last digit with modulo, shrink with division.

3. Palindrome Check

Build reversed half while dividing — classic interview prep.

Example: compare original with reversed digits.

4. String Alternative

Same output with substr — see Example 3.

Example: no arithmetic, just shorter string prefixes.

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: re-prompt when user enters 0.

Pro Tip: always print before dividing — dividing first skips the original value on the first line.

Advantages

Why this pattern earns a spot in beginner PHP courses.

  1. 1. One Simple Loop

    No nested loops — easier than grid patterns in Program 59.

  2. 2. Teaches Integer Division

    / 10 and % 10 are core digit-manipulation tools.

  3. 3. Easy to Extend

    Try string variant, negative handling, or continue to Program 61.

  4. 4. O(1) Extra Memory

    Only one integer variable changes — no arrays needed.

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

Usage Tips

Small habits that keep digit-removal code correct.

  1. 1. Echo Before Divide

    Always echo $num . 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 single digit has been printed and divided.

  4. 4. Handle Zero Input

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

  5. 5. Try $num = intdiv($num, 10)

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

Pro Tip: if output is missing the first number, you divided before printing.

Common Pitfalls

Mistakes that commonly break digit-removal patterns.

  1. 1. Dividing Before Printing

    First line shows 8652 instead of 86523 — you skipped the original value.

    → Print $num 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 double can introduce precision issues on very large values.

    → Use int or long 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

Negative num

Use 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 long if values exceed Integer.MAX_VALUE.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Change starting number

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

2. Print removed digits

  • Use $num % 10 before dividing
  • Show which digit was dropped each step

3. String variant

  • Rewrite with substr — Example 3
  • Compare output with division version

4. Next in series

  • Continue with Program 61
  • Progressive reverse build from same number

Notes

  • Digit count. Loop runs once per digit — O(d) time for d digits.
  • / 10 removes last digit; % 10 extracts it — pair them in Program 61.
  • Validate $num != 0 for interactive programs; zero input prints nothing.
  • Compare with Program 59 (nested grid loops) — this pattern needs only one while loop.

Quick Takeaway: echo $num, 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 substr (Example 3)O(d²)O(d) for string
Wrap Up

🎉 Conclusion

The remove-last-digit pattern is a compact while-loop lesson: print the value, 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 61 for the progressive reverse-build pattern.

Print before divide — loop while $num != 0 — O(d) time for d digits.

💡 Best Practices

✅ Do

  • Print $num 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 printing the current value
  • Forget to update $num inside the loop
  • Use floating-point types for digit removal
  • Ignore zero input in user-facing demos
  • Skip the single-digit edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this digit-removal pattern

One while loop, integer division, O(d) time.

5
Core concepts
02

While loop

$num != 0

Code
/ 03

Division

intdiv($num, 10)

Code
04

Stops at 0

Zero not printed

Edge
O 05

Complexity

O(d) time

Analysis

❓ Frequently Asked Questions

Integer division discards the remainder. So intdiv(86523, 10) becomes 8652, intdiv(8652, 10) becomes 865, and so on.
The loop prints $num then divides. When $num becomes 0, while ($num != 0) is false — 0 is never printed.
Yes, but use abs($num) first so output has no leading minus on every line.
Yes. Convert to string and print substr($s, 0, $len) — see Example 3.
intdiv(120, 10) becomes 12 immediately — trailing zeros drop like any other last digit.
Yes. Use fgets(STDIN) with is_numeric() and the same while-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.
Yes for non-negative numbers: $num = (int) floor($num / 10) behaves like intdiv($num, 10).

Did you Know? 🔊

Integer division by 10 drops the last digit each step — 86523 becomes 8652, then 865, 86, 8. One while loop, O(d) time for d digits. Prefer intdiv($num, 10) (or (int) floor($num / 10)) in PHP.

Continue to Program 61

Move on to the progressive reverse-build number pattern in the PHP number-pattern series.

Program 61 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