How to use Nested Loops In PHP
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:
* *** ***** ******* ********* ******* ***** *** *
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.