PHP Program to Print Pyramid
In this article write a PHP Program to Print Pyramid pattern. This Program first takes the numbers of rows and then prints pattern using nested for loops. This kind of problems are useful for beginners to understands the fundamentals of for loops and spaces.
PHP program to Print Pyramid Pattern using * and loop.
<?php echo "<pre>"; $space = 10; for ($i = 0; $i <= 10; $i++) { for ($k = 0; $k < $space; $k++) { echo " "; } for ($j = 0; $j < 2 * $i - 1; $j++) { echo "*"; } $space--; echo "<br/>"; } echo "</pre>"; ?>
Output:
Explanation:
The program is used to build a pyramid using * (asterisk) and for that you have to understand the for loop which is implemented inside the program.
$i = 0 till 10
$k = 0 till $k < $space
echo " ";
$j = 0 till $j= 2 * $i - 1
and inside that loop block prints the asterisk (*) symbol. Outside the inner for loop, you have to decrement the value of variable $space by 1
echo "<br/>";
Great Examples!
ohh thanks
awesome, and simple, and very clear to understand.
I’m glad it helped you. Happy coding.
best example
Thanks Atpalwad Pravin
Fantastic data, Appreciate it!|
Alternative approach, building a multi dimensional array containing all the values of the pyramid.
<?php
$n = 10;
$pyramid = [];
for ($i = 1; $i < $n; $i++) {
$pyramid[$i] = array_pad([], $n * 2 – 1, ' ');
$middlePoint = floor(($n * 2 – 1) / 2);
for ($starIndex = $middlePoint – ($i – 1); $starIndex <= $middlePoint + ($i – 1); $starIndex++) {
$pyramid[$i][$starIndex] = '*';
}
}
echo '’;
foreach ($pyramid as $row) {
echo implode(”, $row).”\n”;
}
echo ”;
It helped me alot sir. Very simple code
It helped me alot sir. Very simple code
plz help me sir
yes sure
1
2 4
1 3 7
2 4 6 8
1 3 7 9 11
and another is
1
13
137
17379
137911