Centered Number Diamond in PHP

What You’ll Learn
How to print a centered number diamond in PHP by combining an increasing pyramid and a decreasing pyramid.
You’ll practice nested loops for leading spaces and row-wise number printing with odd-length sequences.
⭐ Pattern Output
For n = 5, the pattern looks like this:
1
123
12345
1234567
123456789
1234567
12345
123
1Complete PHP Program
First print the upper half (increasing width), then the lower half (decreasing width).
<?php
// First Part
for ($i = 1; $i <= 5; $i++) {
for ($j = $i; $j < 5; $j++) {
echo " ";
}
for ($k = 1; $k < $i * 2; $k++) {
echo $k;
}
echo PHP_EOL;
}
// Second Part
for ($i = 4; $i >= 1; $i--) {
for ($j = 5; $j > $i; $j--) {
echo " ";
}
for ($k = 1; $k < $i * 2; $k++) {
echo $k;
}
echo PHP_EOL;
}🧠 How It Works
Upper half loop
for ($i = 1; $i <= 5; $i++) builds rows from narrow to wide.
Leading spaces
The space loop controls indentation so rows stay centered.
Odd-width number row
for ($k = 1; $k < $i * 2; $k++) prints 2i - 1 numbers (1, 3, 5, ...).
Lower half loop
for ($i = 4; $i >= 1; $i--) mirrors the top, forming the diamond.
Centered number diamond
Two mirrored pyramids create the full diamond. Complexity is approximately O(n²) for height n.
Variation — User Input (CLI) Version
This version lets users choose the height at runtime (run from terminal with php):
<?php
echo "Enter the height: ";
$n = (int) trim(fgets(STDIN));
if ($n < 1) {
echo "Height must be at least 1" . PHP_EOL;
exit;
}
for ($i = 1; $i <= $n; $i++) {
for ($j = $i; $j < $n; $j++) {
echo " ";
}
for ($k = 1; $k < $i * 2; $k++) {
echo $k;
}
echo PHP_EOL;
}
for ($i = $n - 1; $i >= 1; $i--) {
for ($j = $n; $j > $i; $j--) {
echo " ";
}
for ($k = 1; $k < $i * 2; $k++) {
echo $k;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Replace hardcoded
5with a variable for dynamic size - Add spaces between numbers for wider visual separation
- Print descending numbers for each row (e.g., 54321)
- Swap digits with symbols to create hybrid patterns
- Store rows in arrays before printing for reuse
Avoid
- Changing number loop bounds without adjusting spacing
- Forgetting to print the mirrored lower half
- Using invalid input values without checks
- Mixing tabs/spaces inconsistently in printed indentation
Key Takeaways
The pattern is built from two parts: increasing and decreasing pyramids.
Each row prints odd-width sequences using 2i - 1.
Leading spaces keep every row centered.
The same approach applies to star patterns and alphabet patterns.
❓ Frequently Asked Questions
i = 5, and width is 2i - 1 = 9.n in the loop bounds. More rows produce a taller and wider diamond.echo $k; with echo $k . " ";, then adjust leading spaces for alignment.Explore More PHP Number Patterns!
Practice nested-loop logic by building more centered and mirrored number layouts.
Diamond-like patterns are often taught to explain how row index controls both indentation and content width at the same time.
12 people found this page helpful
