'Print pattern of increasing asterisks and zeros

How to print this Pattern?

pattern

$number = 5;
for ($i=1; $i <= $number ; $i++) { 
    for ($j=$i; $j >= 1;$j--){
        echo "0";
    }
    echo "\n";
}

Prints

0
00
000
0000
00000

I've tries like this, but i'm confused to print star and Zero char

for ($i=1; $i <= $number ; $i++) { 
    $sum = 0;
    for ($j=$i; $j >= 1;$j--){
        $sum +=$j;
    }
    echo $i ." => " .$sum ."\n";
}

Prints

1 => 1
2 => 3
3 => 6
4 => 10
5 => 15
php


Solution 1:[1]

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

Solution 2:[2]

The number of zeros are equal to $i in the for loop. So we just need to calculate the number of stars and then simply do a str_repeat

$count = 5;

for ($i=1; $i <= $count; $i++) {

  $stars = 0;
  for($j=1; $j <= $i; $j++) {
    $stars = $stars + $j;
  }

  echo str_repeat('*', $stars).str_repeat('0', $i)."\n";
}

Output:

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

Solution 3:[3]

$line = '';

for ($i = 1; $i <= 5; $i++) {

   $line = str_repeat('*', $i) . $line . '0'; // **str_repeat()** --> getting string length

   echo $line . PHP_EOL; // **PHP_EOL** ---> represents the endline character.

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Biegeleisen
Solution 2 Parto
Solution 3 Elbo Shindi Pangestu