Rotating Number Sequence in PHP

What You’ll Learn
How to print a rotating number sequence pattern in PHP using two inner loops per row.
You’ll combine a descending segment and an ascending segment to generate each line.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
12345
21234
32123
43212
54321Complete PHP Program
The first loop prints the left descending part, and the second loop prints the remaining ascending part.
<?php
for ($i = 1; $i <= 5; $i++) {
for ($j = $i; $j > 1; $j--) {
echo $j;
}
for ($k = 1; $k <= 6 - $i; $k++) {
echo $k;
}
echo PHP_EOL;
}🧠 How It Works
Outer loop controls rows
for ($i = 1; $i <= 5; $i++) prints one line per row.
First inner loop (descending)
for ($j = $i; $j > 1; $j--) prints $i, $i-1, ..., 2.
Second inner loop (ascending)
for ($k = 1; $k <= 6 - $i; $k++) completes the row with ascending numbers.
New line
echo PHP_EOL; moves to the next output row.
Shifted sequence rows
Each row prints exactly n digits, so runtime is O(n²) for n rows.
Variation — User Input (CLI) Version
This version lets users choose pattern size at runtime (run from terminal with php):
<?php
echo "Enter number of rows: ";
$n = (int) trim(fgets(STDIN));
if ($n < 1) {
echo "Rows must be at least 1" . PHP_EOL;
exit;
}
for ($i = 1; $i <= $n; $i++) {
for ($j = $i; $j > 1; $j--) {
echo $j;
}
for ($k = 1; $k <= ($n + 1) - $i; $k++) {
echo $k;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Add spaces between digits for easier readability
- Reverse the loops to generate mirrored variants
- Use letters instead of numbers for alphabet rotation
- Create a function to reuse the pattern for any n
- Store rows in an array before rendering
Avoid
- Hardcoding bounds when you need dynamic size
- Skipping validation for non-positive inputs
- Mixing descending/ascending loop bounds incorrectly
- Forgetting newline after each completed row
Key Takeaways
Two inner loops combine descending and ascending segments per row.
The pattern gradually rotates from 12345 to 54321.
Loop bounds are tightly connected to the row index $i.
Same logic style can build many circular/shifted patterns.
❓ Frequently Asked Questions
$i = 3, first loop prints 3,2 and second loop prints 1,2,3, producing 32123.$n and replace fixed value 5 with $n in all related bounds.echo and optionally trim() each row output.Explore More PHP Number Patterns!
Practice sequence transformations with more loop-based number designs.
Patterns like this are great for understanding how multiple loops can cooperate to build one line from two different directional sequences.
12 people found this page helpful
