PHP Star Pattern Programs

Beginner
8 min read
Updated: Sep 2026
11 patterns
Live preview

What Is This Pattern?

Star pattern programs print * and spaces in rows to form triangles, pyramids, diamonds, and hollow shapes. They are the classic first step into nested for loops in PHP.

Remember
Starter rule (Program 1): on row i, print i stars

*
**
***
****
*****     ← 5 rows

Learn the right-angled triangle first, then reuse the same outer-row idea for inverted shapes, leading spaces, and mirrored halves. This hub teaches that foundation, then links to all 11 tutorials.

How to Solve It

Start with nested loops for the starter triangle, then optionally shorten with str_repeat.

MethodIdeaBest for
Nested loopsOuter = rows, inner = stars via echo "*"Learning, interviews, exams
str_repeat("*", $i)Build a whole row in one callShorter demos once loops click
Spaces + starsAdd a space loop before the star loopRight-aligned / centered shapes (Programs 3–6)

Pseudocode

Pseudocode
for i from 1 to rows:
    for j from 1 to i:
        print "*" (no newline)
    print newline

Cheat sheet

GoalPattern
Walk each rowfor ($i = 1; $i <= $rows; $i++)
Print i starsfor ($j = 1; $j <= $i; $j++) echo "*";
End the rowecho PHP_EOL;
One-line row shortcutecho str_repeat("*", $i) . PHP_EOL;
Invert laterfor ($i = $rows; $i >= 1; $i--) → Program 2
Add leading spacesecho str_repeat(" ", $rows - $i); → Program 3

Write vs WriteLine

APIEffectUse for
echo "*"Stays on the same lineEach * (and each space)
echo PHP_EOLEnds the current lineAfter the inner loop

Same idea as C# Write / WriteLine: print characters without a newline, then end the row once.

Live Preview

Change the row count and the starter triangle updates instantly — including the triangular star total.

Whole numbers from 1 to 20. Tap a chip or type a value — the preview redraws as you go.

Live result 5 rows · 15 stars
*
**
***
****
*****

Worked Walkthrough — rows = 4

Trace each outer-loop value of i and count how many times the inner loop runs.

iInner jPrinted rowStars
11..1*1
21..2**2
31..3***3
41..4****4

Total star prints: 1 + 2 + 3 + 4 = 10 = 4×5/2. That triangular sum is why time is O(n²).

PHP Programs

Three starter programs for the right-angled triangle: fixed rows, CLI input, and str_repeat. Use View Output to reveal sample results. Full deep-dives live in each program page.

Example 1 — Fixed rows = 5

Hard-coded height — ideal for first demos and screenshots.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo "*";
    }
    echo PHP_EOL;
}
?>

How It Works

1. Set height. $rows = 5 means the triangle has five lines.

2. Outer loop picks the row. $i runs from 1 to $rows.

3. Inner loop prints stars. For each $i, $j runs from 1 to $i, so row $i gets exactly $i stars via echo "*".

4. Break the line. echo PHP_EOL; after the inner loop starts the next row.

When $i = 1 you get *; when $i = 2 you get **; and so on up to five stars.

Example 2 — User Input Version

Read the row count from the CLI. Prefer is_numeric in real apps (shown in the tip below).

PHP
<?php
echo "Enter the number of rows: ";
$rows = (int) trim(fgets(STDIN));

for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo "*";
    }
    echo PHP_EOL;
}
?>

How It Works

1. Prompt and read. fgets(STDIN) returns a line; trim drops the newline, then cast to int.

2. Same nested-loop core. Only the source of $rows changes — the print logic matches Example 1.

3. Safer input tip. Bare (int) casts turn letters into 0. Prefer:

Safer input
echo "Enter the number of rows: ";
$input = trim(fgets(STDIN));
if (!is_numeric($input) || (int) $input < 1) {
    echo "Enter a positive whole number." . PHP_EOL;
    exit(1);
}
$rows = (int) $input;

Example 3 — str_repeat("*", $i)

Build each row in one call — same shape, no explicit inner star loop.

PHP
<?php
$rows = 5;

for ($i = 1; $i <= $rows; $i++) {
    echo str_repeat("*", $i) . PHP_EOL;
}
?>

How It Works

1. One outer loop. Still walk $i from 1 to $rows.

2. Build the row. str_repeat("*", $i) creates a string of length $i filled with stars.

3. Print and advance. Concatenate PHP_EOL so each row ends cleanly.

Learn the two-loop version first (Examples 1–2) so you can explain both bounds in an interview; treat this as a polish shortcut afterward.

Edge Cases & Pitfalls

Check these before calling any star-pattern solution done.

PHP_EOL inside

Column of stars

If echo "*\n" or echo PHP_EOL sits inside the inner loop, each star lands on its own line. Use bare echo "*" for stars; end the row only after the inner loop.

Off-by-one

Wrong height

Use $i = 1; $i <= $rows for 1..rows. Starting at 0 or stopping at < $rows usually breaks the star count.

j to rows

Rectangle, not triangle

Inner bound must be $j <= $i. Looping to $rows every time prints a filled rectangle.

No PHP_EOL

One endless line

Omitting the row break glues every star onto a single line.

rows = 1

Single star

Output is just * on one line — a good sanity check for any pattern.

rows ≤ 0

Empty output

Outer loop never runs. Validate and re-prompt for interactive programs.

Bad input

Check is_numeric

Bare (int) casts turn non-numeric strings into 0 — prefer is_numeric before casting.

Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
str_repeat (Example 3)O(rows²)O(rows) per temporary row string
Typical series (Programs 1–11)O(rows²)O(1) for loop versions

For the starter triangle, total stars = n(n+1)/2. Wider or two-half shapes still print a quadratic number of characters in n.

Key Takeaways

  • Skeleton: outer loop = rows; inner loops = spaces and/or stars.
  • Starter rule: on row i, print exactly i stars.
  • Break the row: echo "*" for characters; echo PHP_EOL after the inner loop.
  • Complexity: expect O(n²) time for almost every shape in this series.

One line: for each row i, print the right number of spaces and stars with echo, then call echo PHP_EOL.

Complete List of PHP Star Patterns

Below are 11 star pattern programs. Each card shows sample output; open it for the full program, logic breakdown, and FAQs.

Frequently Asked Questions

They print asterisks and spaces in rows to form triangles, pyramids, diamonds, and hollow shapes. Nested for loops plus echo and PHP_EOL are the usual tools.
Start with Program 1 (right-angled triangle). It teaches the outer-row / inner-star idea every later pattern builds on.
The outer loop runs i from 1 to rows. For each row i, the inner loop runs j from 1 to i and prints a star with echo. Row 1 prints 1 star, row 2 prints 2 stars, and so on.
echo "*" stays on the same line with no newline. echo PHP_EOL ends the current line. Stars use echo; the row break uses echo PHP_EOL after the inner loop.
Yes. echo str_repeat("*", $i) . PHP_EOL prints a full row in one call. Nested loops are better for learning; str_repeat is a handy shortcut later.
Most print O(n²) characters for n rows. The starter triangle prints n(n+1)/2 stars; wider or two-half shapes stay quadratic in n.
Use trim(fgets(STDIN)), check is_numeric($input), then cast to int and require rows >= 1.
Add a space loop before the star loop for centering, then mirror the upper half for inverted or diamond shapes. See Programs 5–11.

Did you know?

Almost every star pattern is the same idea: an outer loop picks the row, then inner loops decide spaces and stars. Master the right-angled triangle first — the rest reuse that skeleton.

Ready for the full walkthrough?

Open Program 1 for a dedicated tutorial, then move through inverted, centered, and diamond shapes.

Program 1 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

28 people found this page helpful