How to use Single Loop and String Manipulation In PHP

An alternative approach involves using a single loop and string manipulation to create each row.

PHP




<?php
  
function printDiamond($rows) {
    for ($i = 1; $i <= $rows; $i++) {
        echo str_repeat(" ", $rows - $i);
        echo str_repeat("*", 2 * $i - 1) . "\n";
    }
  
    for ($i = $rows - 1; $i >= 1; $i--) {
        echo str_repeat(" ", $rows - $i);
        echo str_repeat("*", 2 * $i - 1) . "\n";
    }
}
  
// Driver code
$row = 5;
printDiamond($row);
  
?>


Output:

        
       *
      ***
     *****
    *******
   *********
    *******
     *****
      ***
       *


PHP Program to Print Diamond Shape Star Pattern

Printing a diamond-shaped star pattern is a classic programming exercise that involves nested loops to control the structure of the pattern. In this article, we will explore different approaches to creating a PHP program that prints a diamond-shaped star pattern.

Similar Reads

Using Nested Loops

The basic method involves using nested loops to control the number of spaces and stars in each row. The nested loop prints spaces and stars for each row, creating a diamond-shaped pattern. The number of rows determines the size of the diamond....

Using Single Loop and String Manipulation

...