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.