Descending Numbers with Diagonal * in PHP

What You’ll Learn
How to print a descending number pattern in PHP where a diagonal position is replaced with an asterisk:
5432*, 543*1, 54*21, 5*321, *4321.
This pattern is a great way to practice nested loops and a simple if condition.
⭐ Pattern Output
For $n = 5, the pattern looks like this:
5432*
543*1
54*21
5*321
*4321Complete PHP Program
We print $j from $n down to 1, but if $i === $j we print * instead.
<?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
Set n
$n = 5; defines the range of numbers printed on each row.
Outer loop (rows)
for ($i = 1; $i <= $n; $i++) moves the diagonal position one step each row.
Inner loop (descending numbers)
for ($j = $n; $j >= 1; $j--) prints numbers from 5 down to 1 on each line.
Replace diagonal with *
When $i === $j, we print * instead of the number.
Diagonal star
The matching $i and $j values create a diagonal of asterisks across the output.
Variation — User Input (CLI) Version
Let the user choose $n at runtime (run from terminal with php):
<?php
echo "Enter n (e.g., 5): ";
$n = (int) trim(fgets(STDIN));
if ($n < 1) {
echo "Please enter a positive number." . PHP_EOL;
exit(1);
}
for ($i = 1; $i <= $n; $i++) {
for ($j = $n; $j >= 1; $j--) {
echo ($i === $j) ? "*" : $j;
}
echo PHP_EOL;
}💡 Tips for Enhancement
Try These
- Replace
*with another symbol to create different diagonal effects - Print spaces between numbers for readability when
$nis large - Create the opposite diagonal by checking
$i + $j === $n + 1 - Turn it into an X pattern by printing stars on both diagonals
- Use
printfpadding to align multi-digit numbers
Avoid
- Mixing loop directions unintentionally (this pattern expects j to count down)
- Forgetting the newline after each row
- Skipping input validation for CLI mode
- Assuming single-digit formatting for large n values
Key Takeaways
The inner loop prints descending values from $n to 1.
The condition $i === $j identifies the diagonal position.
Replacing one position per row creates a clean diagonal effect.
The same idea can build X patterns and other matrix-like designs.
❓ Frequently Asked Questions
$i + $j === $n + 1 instead of $i === $j.* when $i === $j or $i + $j === $n + 1.$j = $n and decrements down to 1.Explore More PHP Number Patterns!
Diagonal conditions like these are the building blocks for many grid and matrix patterns.
In grid problems, diagonals are commonly detected with i === j (main diagonal) and i + j === n + 1 (anti-diagonal).
12 people found this page helpful
