A PHP star pattern is a script that prints * in rows. The outer for loop chooses the row. The inner for loop echos each star, then echo PHP_EOL ends that row.
echo "*" does not add a newline, so stars sit next to each other. The + operator does not add a star: '*' + 1 is the number 1, because PHP casts '*' to 0. Two stars are "*" . "*", or str_repeat("*", 2).
str_repeat prints a whole run.
echo str_repeat("*", $row) . PHP_EOL writes one solid row. Use the inner loop when that row mixes spaces and stars.
Syntax
PHP Syntax
The inner loop runs once per star. echo "*" stays on the row, and PHP_EOL comes after that loop.
PHP
<?php
for ($row = 1; $row <= $rows; $row++) {
for ($col = 1; $col <= $row; $col++)
echo "*"; // same row
echo PHP_EOL; // end the row
}
Reference
How PHP Prints a Star
Map each part of the console shape to a PHP value or call.
Piece
PHP
What it does
Star
echo "*"
Writes one star and stays on the row
Run of stars
str_repeat("*", $n)
A string of $n stars
Indent
str_repeat(" ", $n)
$n spaces
Join
"*" . "*"
The string "**"
Numeric +
"*" + 1
Addition: "*" becomes 0
New row
echo PHP_EOL
Ends the row
Edge only
echo ($col == 1 || $col == $width) ? "*" : " "
A hollow row
Code
PHP Examples
Three scripts. Each one changes only the PHP that chooses how many stars to print, and where the spaces go.
Example 1 — One star per inner-loop pass
Row 1 echoes one star. Each later row echoes one more, because the inner loop stops at $row.
The + operator adds. PHP casts '*' to 0, so '*' + 1 is 1. A star is echo "*". Two stars are "*" . "*", or str_repeat("*", 2).
echo "*" writes the star and stays on the same row. echo PHP_EOL ends the row. "\n" does the same break in a CLI script. If echo PHP_EOL is inside the inner loop, each star lands on its own line.
Yes, when the row is a solid run of stars. echo str_repeat("*", $row) . PHP_EOL prints that row in one call. Use the inner loop when the row mixes spaces and stars, or when only the edges should be stars.
Print the indent first: echo str_repeat(" ", $rows - $row). Then echo str_repeat("*", 2 * $row - 1). echo PHP_EOL ends the row. Row 1 has one star; each later row adds two.