PHP Number-Star Diamond Pattern

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

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.

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.

MethodIdeaBest for
Two halves + modulusTop 1..$n, bottom $n-1..1; even $j → *Learning, interviews, exams
Ternary formecho ($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

GoalPattern
Top halffor ($i = 1; $i <= $n; $i++)
Bottom halffor ($i = $n - 1; $i >= 1; $i--)
Row lengthfor ($j = 1; $j < $i * 2; $j++) → 2*$i-1 chars
Alternateif ($j % 2 == 0) echo "*"; else echo $i;
End of rowecho PHP_EOL;

Printing Numbers vs Starting a New Line

APIEffectUse for
echo $i / "*"Stays on the same lineEach digit or star on the row
echo PHP_EOLEnds the current lineAfter the inner loop finishes

Print characters without a newline, then end the row once.

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 result n = 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

Worked Walkthrough — Top Half $n = 5

Trace how each top-half row builds 2*$i−1 characters. The bottom half repeats rows 4..1.

$iCharsPatternPrints
11i1
23i * i2*2
35i * i * i3*3*3
47i * … * i4*4*4*4
59peak5*5*5*5*5

Top half = n² chars; bottom = (n−1)². Total lines = 2n − 1 → O(n²).

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.

PHP
<?php
for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j < $i * 2; $j++) {
        if ($j % 2 == 0) {
            echo "*";
        } else {
            echo $i;
        }
    }
    echo PHP_EOL;
}

for ($i = 4; $i >= 1; $i--) {
    for ($j = 1; $j < $i * 2; $j++) {
        if ($j % 2 == 0) {
            echo "*";
        } else {
            echo $i;
        }
    }
    echo PHP_EOL;
}
?>

How It Works

1. Top half grows. $i from 1 to 5 builds longer rows up to the peak.

2. Modulus alternates. Odd $j prints $i; even $j prints *.

3. Bottom mirrors. Second loop starts at $n - 1 so the peak is not printed twice.

Example 2 — User Input Height

Read $n from the CLI, validate, then use ternary conditions for each position.

PHP
<?php
echo "Enter n: ";
$input = trim(fgets(STDIN));

if (!is_numeric($input) || (int) $input <= 0) {
    echo "Please enter a positive integer." . PHP_EOL;
    exit(1);
}

$n = (int) $input;

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

1. Prompt and validate. Reject non-numeric and non-positive values before printing.

2. Same core. Ternary form matches Example 1’s if/else — only $n comes from the user.

3. Safer input tip. Cap demos for readable output:

Safer input
if (!is_numeric($input) || (int) $input < 1 || (int) $input > 7) {
    echo "Enter a whole number from 1 to 7." . PHP_EOL;
    exit(1);
}

Example 3 — Compact $n = 3

Same structure with a small peak — easy to confirm the bottom starts at $n - 1.

PHP
<?php
$n = 3;

for ($i = 1; $i <= $n; $i++) {
    for ($j = 1; $j < $i * 2; $j++) {
        if ($j % 2 == 0) {
            echo "*";
        } else {
            echo $i;
        }
    }
    echo PHP_EOL;
}

for ($i = $n - 1; $i >= 1; $i--) {
    for ($j = 1; $j < $i * 2; $j++) {
        if ($j % 2 == 0) {
            echo "*";
        } else {
            echo $i;
        }
    }
    echo PHP_EOL;
}
?>

How It Works

1. Five lines. Peak 3*3*3 appears once; bottom starts at $i = 2.

2. Trace on paper. If the bottom loop starts at $n, the peak prints twice.

3. Scale up next. Once the small demo is clear, use Examples 1–2 for height 5 or user input.

Edge Cases & Pitfalls

Check these before calling the solution done.

i = n

Doubled peak

Starting the bottom loop at $n reprints the widest row. Use $i = $n - 1.

j <=

Wrong row length

$j <= $i * 2 adds an extra character. Keep $j < $i * 2 for exactly 2*$i-1 chars.

% flip

Stars in wrong spots

Even $j must print * and odd $j must print $i — flipping them breaks the pattern.

PHP_EOL inside

Broken rows

If echo PHP_EOL sits inside the inner loop, you get one character per line. Call it only after the loop.

n = 1

Single digit

Output is just 1 — the bottom loop never runs. A good sanity check for input validation.

fgets

Check is_numeric

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

Time and Space Complexity

ProgramTimeExtra space
Fixed / input (Examples 1–2)O(n²)O(1)
Compact n = 3 (Example 3)O(n²)O(1)

Top half prints n² characters; bottom prints (n−1)². Total ≈ 2n² → O(n²) time. Only a few loop variables are needed.

Key Takeaways

  • Two halves: top 1..$n, bottom $n-1..1 so the peak appears once.
  • Modulus rule: odd $j → digit $i; even $j → *.
  • Break the row: characters in the inner loop; echo PHP_EOL after it finishes.
  • Complexity: O(n²) time from both halves; O(1) extra space.

One line: for each half, print 2*$i−1 chars alternating $i and *, then echo PHP_EOL.

Frequently Asked Questions

A number-star diamond: for n=5 you get 1 / 2*2 / 3*3*3 / 4*4*4*4 / 5*5*5*5*5, then the same rows mirrored back down to 1.
The inner loop runs while $j < $i*2, which prints 1, 3, 5, 7, 9 characters for $i = 1..5.
It checks $j % 2. Even $j prints '*', odd $j prints the current row number $i.
The first loop builds the top half ($i = 1..$n). The second mirrors back down ($i = $n-1..1) to complete the diamond.
Program 30 is a right-aligned descending triangle. Program 31 alternates digits and stars in a symmetric diamond shape.
echo $i (or "*") stays on the same line. echo PHP_EOL ends the row after the inner loop finishes.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int — see Example 2.
O(n²) for height n because total printed characters grow as n² + (n-1)² across both halves.

Did you know?

This pattern prints a top half (1..$n) and a bottom half ($n-1..1). Each row prints 2*$i-1 characters, alternating the row number and * using $j % 2.

Next: Increasing Triangle from 11

Continue with a triangle that starts counting from 11.

Program 32 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

12 people found this page helpful