An inverted center-aligned pyramid prints the widest odd-width star row first, then narrows to a single tip star — with leading spaces so each shorter row stays centered.
Remember
Rule: for i from rows down to 1,
print (rows - i) spaces, then (2 * i - 1) stars
*********
*******
*****
***
* ← 5 rows (base on top)
It is the flip of Program 5: keep the same space and star formulas, reverse only the outer loop. That mirrors how Program 2 inverts Program 1, but with odd-width centering.
Approach
How to Solve It
Two ways to emit the same shape — start with nested loops, then optionally shorten with str_repeat.
Method
Idea
Best for
Nested loops
Countdown $i; spaces then odd stars via echo
Learning, interviews, exams
str_repeat
Build margin and star run in one expression
Shorter demos once formulas click
Pseudocode
Pseudocode
for i from rows down to 1:
for j from 1 to (rows - i):
echo " "
for k from 1 to (2 * i - 1):
echo "*"
echo PHP_EOL
Flip of Program 5: same formulas — only reverse the outer loop.
Break the row: call echo PHP_EOL only after both space and star loops.
Complexity:O(n²) time from n² stars; O(1) extra space for nested loops.
One line: for $i from $rows down to 1, print $rows - $i spaces and 2 * $i - 1 stars, then echo PHP_EOL.
Frequently Asked Questions
The outer loop runs i from rows down to 1. Stars still use 2*i-1, so large i prints many stars first. As i shrinks, stars become 9,7,5,… and spaces (rows-i) grow from 0 upward. Same formulas as Program 5 — only the order of i changes.
Spaces use (rows-i). When i is rows, the margin is 0; when i is 1, the margin is rows-1. As i steps down, the margin grows while 2*i-1 shrinks, which keeps shorter rows centered under the wide top.
Program 5 uses for ($i = 1; $i <= $rows; $i++) so stars grow. Program 6 uses for ($i = $rows; $i >= 1; $i--) with the same inner loops, so the base prints first and the tip last.
Program 2 is an inverted left-aligned triangle (i stars, no centering). Program 6 keeps (rows-i) spaces and odd star runs so the tip stays centered.
echo sends output without adding a line break. PHP_EOL ends the current line with a portable newline. Spaces and stars use echo; the row break uses echo PHP_EOL after both inner loops.
O(n²) for n rows. Same totals as Program 5; only iteration order differs. Total stars equal n².