Concentric Descending-Ascending Number Pattern in PHP

What You’ll Learn
How to print a concentric descending-ascending number pattern in PHP using nested loops and if conditions.
This pattern is useful for understanding mirrored output and how row/column comparisons can shape number layouts.
⭐ Pattern Output
For $k = 5, the pattern looks like this:
5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5Complete PHP Program
The row value $i defines the inner zone; outer columns keep their own values.
<?php
$k = 5;
for ($i = $k; $i >= 1; $i--) {
for ($j = $k; $j >= 1; $j--) {
if ($j > $i) {
echo $j . " ";
} else {
echo $i . " ";
}
}
for ($j = 2; $j <= $k; $j++) {
if ($j > $i) {
echo $j . " ";
} else {
echo $i . " ";
}
}
echo PHP_EOL;
}🧠 How It Works
Set size value
$k = 5; controls both height and row width (2k - 1).
Outer loop controls rows
for ($i = $k; $i >= 1; $i--) moves from outer layer to inner layer.
Left and right halves
First inner loop prints from $k..1, second prints from 2..$k to mirror the row.
Conditional value selection
If $j > $i, print $j; otherwise print $i. This fills the center with lower values.
Concentric mirrored rows
Each row has 2k-1 values, and total work is O(k²).
Variation — User Input (CLI) Version
This version accepts the size from user input (run from terminal with php):
<?php
echo "Enter the size: ";
$k = (int) trim(fgets(STDIN));
if ($k < 1) {
echo "Size must be at least 1" . PHP_EOL;
exit;
}
for ($i = $k; $i >= 1; $i--) {
for ($j = $k; $j >= 1; $j--) {
echo ($j > $i ? $j : $i) . " ";
}
for ($j = 2; $j <= $k; $j++) {
echo ($j > $i ? $j : $i) . " ";
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Allow custom separators such as commas or tabs
- Print full square pattern (top and bottom) by mirroring rows
- Replace numbers with letters for alphabet-style layers
- Use ternary expressions to simplify repeated conditions
- Store rows in an array before rendering to HTML
Avoid
- Using invalid size values without validation
- Changing loop bounds without keeping row symmetry
- Printing extra spaces if exact formatting is required
- Duplicating logic blocks without refactoring when scaling up
Key Takeaways
The pattern width is 2k - 1 for size k.
Two inner loops create left and right mirrored halves.
The condition picks outer values or row value to form concentric layers.
The same technique can be adapted to star patterns and alphabet patterns.
❓ Frequently Asked Questions
$i = 1, all inner positions fail $j > $i, so they print 1 until the value rises again toward the right edge.$k. For example, $k = 6 prints 6 rows with width 11.trim() before printing.Explore More PHP Number Patterns!
Build stronger loop logic by practicing mirrored and layered number outputs.
Concentric number patterns are a common interview exercise to test nested-loop control and condition design in one compact problem.
12 people found this page helpful
