Truncate Last Digit While Loop Pattern in PHP

What You’ll Learn
How to print a digit-ladder by repeatedly removing the last digit of an integer with floor($num / 10) inside a while loop.
This pattern reinforces loop conditions, integer truncation, and why floor (or intdiv) matters in PHP.
⭐ Pattern Output
Starting from 86523, each line drops the last digit until the value would reach zero (zero itself is not printed):
86523
8652
865
86
8Complete PHP Program
Print the current number, then replace it with floor($num / 10) until it becomes 0.
<?php
$num = 86523;
while ($num != 0) {
echo $num . PHP_EOL;
$num = (int) floor($num / 10);
}🧠 How It Works
Initialize
$num = 86523 sets the starting value (any positive integer works similarly).
Loop while non-zero
while ($num != 0) keeps going until every digit has been stripped.
Print then truncate
Echo the current value, then set $num = floor($num / 10) to drop the last digit.
Stop at zero
After printing 8, $num becomes 0 and the loop exits, so trailing zero is not shown.
Digit ladder
Iterations equal the number of digits in the starting value, so complexity is O(d) for digit count d.
Variation — User Input (CLI) Version
Reads a positive integer from stdin and prints the same truncation ladder (rejects zero or negative input):
<?php
echo "Enter a positive integer: ";
$num = (int) trim(fgets(STDIN));
if ($num <= 0) {
echo "Enter a positive integer greater than 0" . PHP_EOL;
exit;
}
while ($num != 0) {
echo $num . PHP_EOL;
$num = (int) floor($num / 10);
}💡 Tips for Enhancement
Try These
- Use
intdiv($num, 10)for non-negative integers - Print leading zeros on each line for fixed-width display
- Collect lines into an array and
implodefor testing - After the loop, optionally echo a final
0if you want it shown - Log iteration count to relate output length to digit count
Avoid
- Infinite loops: ensure
$numstrictly moves toward0 - Assuming plain
/always returns integers in PHP - Using this exact truncation for negative numbers without adjusting rules
- Using
while (true)without a clear break condition
Key Takeaways
Truncating the last digit is floor(n / 10) (or intdiv(n, 10)) for non-negative n.
The loop condition != 0 controls whether a final zero line appears.
Iteration count matches the number of digits in the original number.
Same idea underlies base conversion and digit-extraction algorithms.
❓ Frequently Asked Questions
floor plus (int) cast, or intdiv, keeps behavior predictable.$num becomes 0 and the loop ends.while loop highlights the stopping condition on zero and avoids knowing digit length in advance.d decimal digits of the starting value.Explore More PHP Number Patterns!
Practice digit manipulation, then combine it with arrays and string reversal for richer patterns.
Extracting digits with division and modulo (% 10) is the standard complement to this truncation-from-the-right trick.
12 people found this page helpful
