Number-Star Diamond Pattern in PHP

What You’ll Learn
How to print a number-star diamond pattern in PHP that grows from 1 to 5 and then shrinks back to 1:
1, 2*2, 3*3*3, ..., 1.
We use two sections: an increasing part (1..n) and a decreasing part (n-1..1).
⭐ Pattern Output
For $n = 5, the pattern looks like this:
1
2*2
3*3*3
4*4*4*4
5*5*5*5*5
4*4*4*4
3*3*3
2*2
1Complete PHP Program
We print 2*$i - 1 characters per row. Odd positions print the number, even positions print *.
<?php
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j < $i * 2; $j++) {
echo ($j % 2 === 0) ? "*" : $i;
}
echo PHP_EOL;
}
for ($i = $n - 1; $i >= 1; $i--) {
for ($j = 1; $j < $i * 2; $j++) {
echo ($j % 2 === 0) ? "*" : $i;
}
echo PHP_EOL;
}🧠 How It Works
Set n
$n = 5; sets the peak row number.
Build the top half
The first outer loop prints rows from 1 up to $n.
Alternate number and *
The inner loop runs 2*$i - 1 times. Even positions print *, odd positions print the number.
Build the bottom half
The second outer loop prints rows from $n-1 back down to 1, forming the diamond shape.
Number-star diamond
Row lengths increase by 2 until the peak, then decrease by 2.
Variation — User Input (CLI) Version
Let the user choose $n at runtime (run from terminal with php):
<?php
echo "Enter n (e.g., 5): ";
$n = (int) trim(fgets(STDIN));
if ($n < 1) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j < $i * 2; $j++) {
echo ($j % 2 === 0) ? "*" : $i;
}
echo PHP_EOL;
}
for ($i = $n - 1; $i >= 1; $i--) {
for ($j = 1; $j < $i * 2; $j++) {
echo ($j % 2 === 0) ? "*" : $i;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Replace
*with another separator like-or| - Center-align the pattern by adding leading spaces on each row
- Print spaces around * for readability:
echo " * " - Use this alternation technique for binary and checkerboard patterns
- Increase n to create a taller diamond
Avoid
- Using
$j <= $i*2(that would add an extra character per row) - Forgetting the bottom-half loop (you’ll get only the top triangle)
- Skipping input validation in CLI mode
- Assuming alignment without adding spaces/padding
Key Takeaways
Each row prints 2*i - 1 characters.
Odd positions print the row number; even positions print *.
Two outer loops form the diamond: increasing then decreasing.
The same technique generalizes to many alternating-symbol patterns.
❓ Frequently Asked Questions
$j < $i * 2, which means it runs for 1..(2*i-1).*, but keep in mind the row won’t look separated unless you add other formatting.Explore More PHP Number Patterns!
Once you master alternation with modulo, you can create many mixed symbol/number designs.
Alternating output by parity (odd/even) is a common trick in patterns, grids, and even UI zebra-striping.
12 people found this page helpful
