Create Pyramid Pattern in PHP Using For Loop

By Shubham G on Dec 03, 2023

This PHP script uses nested `for` loops to print a centered pyramid pattern made up of asterisk (`*`) characters. 


- The outer `for` loop runs 5 times, representing the number of lines in the pattern.

- The first inner `for` loop prints spaces to create the necessary padding on each line so that the pyramid is centered. It runs 5 minus the current line number times, so the number of spaces decreases as you go down the lines.

- The second inner `for` loop prints the asterisks. It runs twice the current line number minus 1 times, so the number of asterisks increases as you go down the lines, creating the shape of the pyramid.

- After the asterisks and spaces are printed for a line, a line break (`<br/>`) is printed to move to the next line.


The size of the pyramid (i.e., the number of lines) can be adjusted by changing the condition in the outer `for` loop. This script is a simple demonstration of how nested loops can be used to create patterns in PHP. It's a great exercise for those learning PHP and wanting to improve their understanding of loops.

<?php

for ($a = 1;$a <= 5;$a++)
{
    for ($b = $a;$b < 5;$b++)
    {
        echo " &nbsp ";
    }

    for ($c = 1;$c < ($a * 2);$c++)
    {
        echo " * ";
    }
    echo "<br/>";
}

?>

Output : 


  • Related Posts
Loading...