Open In App

PHP Program to Print Diamond Shape Star Pattern

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

PHP




<?php
  
function printDiamond($rows) {
    for ($i = 1; $i <= $rows; $i++) {
          
        // Print spaces
        for ($j = 1; $j <= $rows - $i; $j++) {
            echo " ";
        }
          
        // Print stars
        for ($k = 1; $k <= 2 * $i - 1; $k++) {
            echo "*";
        }
  
        echo "\n";
    }
  
    for ($i = $rows - 1; $i >= 1; $i--) {
          
        // Print spaces
        for ($j = 1; $j <= $rows - $i; $j++) {
            echo " ";
        }
  
        // Print stars
        for ($k = 1; $k <= 2 * $i - 1; $k++) {
            echo "*";
        }
  
        echo "\n";
    }
}
  
// Driver code
$row = 5;
printDiamond($row);
  
?>


Output:

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

Using Single Loop and String Manipulation

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:

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads