PHP Descending Number Pattern (Diagonal Asterisk)

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

What Is This Pattern?

A diagonal asterisk pattern prints descending digits n..1 on every row — but replaces the cell where $i == $j with *, so the star marches left each line.

Remember
Rule: for i = 1..n
      for j = n..1:
        print * if i == j, else print j

5432*
543*1
54*21
5*321
*4321     ← n = 5

After Program 25’s bidirectional triangle, this one keeps a fixed width and swaps one digit for a star per row.

How to Solve It

Walk $i from 1 to $n; on each row scan $j from $n down to 1 and swap when indices match.

MethodIdeaBest for
Match indicesInner $j = $n..1; print * when $i == $jLearning, interviews
Custom symbolSame loops; swap * for # (or any char)Quick variants
CLI inputSame loops; read $n with fgets(STDIN)Interactive practice

Pseudocode

Pseudocode
for i from 1 to n:
    for j from n down to 1:
        if i == j:
            print "*"
        else:
            print j
    print newline

Cheat sheet

GoalPattern
Set size$n = 5;
Outer loopfor ($i = 1; $i <= $n; $i++)
Inner loopfor ($j = $n; $j >= 1; $j--)
Diagonal cellif ($i == $j) echo "*";
Other cellselse echo $j;
End rowecho PHP_EOL;
Chars per rowAlways $n

Printing Numbers vs Starting a New Line

APIEffectUse for
echo "*" / echo $jStays on the same lineEach cell
echo PHP_EOLEnds the current lineAfter the inner loop

Print all cells without a newline, then end the row once with echo PHP_EOL. Putting PHP_EOL inside the inner loop prints one character per line.

Live Preview

Change n and the diagonal asterisk pattern updates instantly.

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

Live result n = 5 · chars = 25
5432*
543*1
54*21
5*321
*4321

Worked Walkthrough — $n = 3

Trace each outer $i, where $i == $j hits, and the printed row.

$iStar when $j =Printed row
11 (rightmost)32*
22 (middle)3*1
33 (leftmost)*21

Inner loop always prints n cells. The star slides left as $i grows. Total chars = n².

PHP Programs

Three complete programs: fixed $n = 5, custom symbol #, and CLI input. Use View Output for sample results.

Example 1 — Fixed $n = 5

Hard-coded size — descending inner loop with * when $i == $j.

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

How It Works

1. Outer loop. $i is both the row index and the column value that becomes *.

2. Inner loop. $j counts down from 5 to 1 so digits appear in descending order.

3. Swap. When $i == $j, print *; otherwise print $j. Then echo PHP_EOL.

Example 2 — Custom Symbol #

Same loops; only the diagonal character changes.

PHP
<?php
$n = 5;

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

How It Works

1. Same structure. Outer and inner bounds match Example 1.

2. Only the symbol changes. Replace echo "*" with echo "#" (or any character).

3. Diagonal unchanged. The star still hits when $i == $j and still moves left each row.

Example 3 — CLI Input

Read $n from STDIN so the size is not hard-coded.

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

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

How It Works

1. Read n. Ask for a size, then trim(fgets(STDIN)) and cast to int.

2. Same diagonal rule. Both loops still use $n; only the source of the size changes.

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

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

Edge Cases & Pitfalls

Check these before calling the solution done.

ascending j

Reversed digits

Using $j = 1..$n flips the digit order and moves the diagonal to the opposite side.

echo $i

Wrong fill

Printing $i in the else branch repeats the row number. Use echo $j for column digits.

PHP_EOL inside

Vertical cells

If echo PHP_EOL is inside the inner loop, each character lands on its own line.

anti-diagonal

Different condition

$i + $j == $n + 1 draws the other diagonal — a related but different pattern.

n = 1

Single star

Output is just * — a good sanity check.

fgets

Check is_numeric

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

Time and Space Complexity

ProgramTimeExtra space
Examples 1–3O(n²)O(1)

Each of n rows prints n characters → total n² → O(n²).

Key Takeaways

  • Rule: print n..1; swap to * when $i == $j.
  • Fixed width: every row has exactly $n characters.
  • echo vs PHP_EOL: cells stay on the line; echo PHP_EOL advances after each row.
  • Complexity: total chars = n² → O(n²).

One line: descend n..1 each row and swap the cell where row equals column for *.

Frequently Asked Questions

Because $i increases from 1 to $n while $j decreases from $n to 1. The condition $i == $j becomes true at a different position each row.
$j holds the descending column digit (5, 4, 3, 2, 1). When $i != $j, print that digit to fill the row.
Yes. Replace echo "*" with any character or string — see Example 2 with #.
echo $j prints each digit or star on the same line. echo PHP_EOL ends the row after the inner loop finishes.
$j runs from $n down to 1 so each row prints digits in descending order with the star at position $i.
Replace 5 with $n in both loops — see Example 3 and the live preview.
O(n²) for n rows because each row prints n characters using a nested loop.
Use trim(fgets(STDIN)) and check is_numeric($input) before casting to int.
Only one row prints — a single *.

Did you know?

This pattern prints descending numbers from $n to 1 on each row. When the row index equals the current column value ($i == $j), it prints * instead of the number, creating a diagonal asterisk that moves left each row.

Next: Palindrome Number Triangle

Continue with the next pattern in the PHP number-pattern series.

Program 27 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.

12 people found this page helpful