A number-star diamond grows from 1 to n*n*…*n, then mirrors back down — each row alternates the row number and *.
Remember
Rule: top i = 1..n, bottom i = n-1..1
for j from 1 to 2*i-1:
odd j → print i even j → print *
1
2*2
3*3*3
4*4*4*4
5*5*5*5*5
4*4*4*4
3*3*3
2*2
1 ← n = 5
Follows the right-aligned descending triangle in Program 30; next is the increasing triangle from 11 in Program 32.
Approach
How to Solve It
Two outer loops build the diamond. One shared inner rule: print 2*$i−1 characters, alternating digit and star with $j % 2.
Method
Idea
Best for
Two halves + modulus
Top 1..$n, bottom $n-1..1; even $j → *
Learning, interviews, exams
Ternary form
echo ($j % 2 == 0) ? "*" : $i;
Shorter demos once if/else is clear
Pseudocode
Pseudocode
for i from 1 to n:
for j from 1 to 2*i - 1:
if j % 2 == 0: print *
else: print i
print newline
for i from n - 1 down to 1:
for j from 1 to 2*i - 1:
if j % 2 == 0: print *
else: print i
print newline
Cheat sheet
Goal
Pattern
Top half
for ($i = 1; $i <= $n; $i++)
Bottom half
for ($i = $n - 1; $i >= 1; $i--)
Row length
for ($j = 1; $j < $i * 2; $j++) → 2*$i-1 chars
Alternate
if ($j % 2 == 0) echo "*"; else echo $i;
End of row
echo PHP_EOL;
Printing Numbers vs Starting a New Line
API
Effect
Use for
echo $i / "*"
Stays on the same line
Each digit or star on the row
echo PHP_EOL
Ends the current line
After the inner loop finishes
Print characters without a newline, then end the row once.
Try it
Live Preview
Change the height and the number-star diamond updates instantly — capped at 7 for readable demos.
Whole numbers from 1 to 7. Tap a chip or type a value — the preview redraws as you go.
Live resultn = 5 · 41 chars
1
2*2
3*3*3
4*4*4*4
5*5*5*5*5
4*4*4*4
3*3*3
2*2
1
Trace
Worked Walkthrough — Top Half $n = 5
Trace how each top-half row builds 2*$i−1 characters. The bottom half repeats rows 4..1.
$i
Chars
Pattern
Prints
1
1
i
1
2
3
i * i
2*2
3
5
i * i * i
3*3*3
4
7
i * … * i
4*4*4*4
5
9
peak
5*5*5*5*5
Top half = n² chars; bottom = (n−1)². Total lines = 2n − 1 → O(n²).
Code
PHP Programs
Three complete programs: fixed $n = 5, CLI input with ternary form, and a compact $n = 3 demo. Use View Output to reveal sample results.
Example 1 — Fixed $n = 5
Hard-coded height — top half grows, bottom half mirrors, if/else on $j % 2.