How to print this pattern using PHP?

You can use str_repeat to generate the strings of required length. Note that for triangular numbers (1, 3, 6, 10, 15, ...) you can generate the i'th number as i(i+1)/2:

$number = 5;
for ($i = 1; $i <= $number; $i++) {
    echo str_repeat('*', $i * ($i + 1) /2) . str_repeat('0', $i) . PHP_EOL;
}

Output:

*0
***00
******000
**********0000
***************00000

Demo on 3v4l.org

For a more literal generation of the triangular part of the output (i.e. sum of the numbers from 1 to i), you could use this code which adds $i *'s and 1 0 to the output on each iteration:

$line = '';
$number = 5;
for ($i = 1; $i <= $number; $i++) {
    $line = str_repeat('*', $i) . $line . '0';
    echo $line . PHP_EOL;
}

Output:

*0
***00
******000
**********0000
***************00000

Demo on 3v4l.org


Here is another way, which uses a more literal reading of the replacement logic. Here, I form each subsequent line by taking the previous line, and adding the line number amount of * to the * section, and then just tag on a new trailing zero.

$line = "*0";
$max = 5;
$counter = 1;

do {
    echo $line . "\n";
    $line = preg_replace("/(\*+)/", "\\1" . str_repeat("*", ++$counter), $line) . "0";
} while ($counter <= $max);

This prints:

*0
***00
******000
**********0000
***************00000

Tags:

Php