Symmetric Increasing-Decreasing Pattern in PHP

What You’ll Learn
How to print a symmetric increasing-decreasing number pattern in PHP using two inner loops.
Each row starts from the row number, increases to a peak, then mirrors back down.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
1
232
34543
4567654
567898765Complete PHP Program
Use one loop for ascending part and another for descending mirror.
<?php
for ($i = 1; $i <= 5; $i++) {
$m = $i;
for ($j = 1; $j <= $i; $j++) {
echo $m++;
}
$m = $m - 2;
for ($k = 1; $k < $i; $k++) {
echo $m--;
}
echo PHP_EOL;
}🧠 How It Works
Outer loop controls rows
for ($i = 1; $i <= 5; $i++) determines row count and starting value.
Ascending part
Start $m = $i, then print and increment in the first inner loop.
Descending part
Set $m = $m - 2 to avoid peak duplication, then print and decrement in second loop.
Move to next row
echo PHP_EOL; ends each line before the next row starts.
Mirrored rows
Each row length is 2i-1, and total work across rows is O(n²).
Variation — User Input (CLI) Version
This version accepts row count from user input (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++) {
$m = $i;
for ($j = 1; $j <= $i; $j++) {
echo $m++;
}
$m -= 2;
for ($k = 1; $k < $i; $k++) {
echo $m--;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Add spaces between digits for readability
- Start from 0 or another base value
- Use characters instead of numbers for mirrored alpha patterns
- Pad rows to create centered visual pyramids
- Wrap logic in a function for reusability
Avoid
- Forgetting to reduce
$mby 2 before descending loop - Using incorrect descending loop bound (
<= $i) - Skipping validation for non-positive row input
- Mixing HTML-only line breaks in CLI examples
Key Takeaways
Each row starts at i and grows upward.
Second loop mirrors the row by printing decreasing values.
$m = $m - 2 prevents repeating the highest middle value.
This approach generalizes to many mirrored number/character patterns.
❓ Frequently Asked Questions
4,5,6,7 first, then descending 6,5,4 to mirror around the peak.$n).Explore More PHP Number Patterns!
Practice mirror-based loop logic with more progressive number designs.
Patterns that combine ascending and descending segments are a classic way to learn how temporary variables carry state between loops.
12 people found this page helpful
