Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP program to print a pattern of pyramid
In PHP, you can print a pyramid pattern using nested loops. The pattern involves printing spaces for centering and asterisks to form the pyramid shape.
Example
Here's how to create a pyramid pattern using a function −
<?php
function print_pattern($val)
{
$num = 2 * $val - 2;
for ($i = 0; $i < $val; $i++)
{
for ($j = 0; $j < $num; $j++)
echo " ";
$num = $num - 1;
for ($j = 0; $j <= $i; $j++ )
{
echo "* ";
}
echo "<br>";
}
}
$val = 7;
print_pattern($val);
?>
Output
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
How It Works
The print_pattern() function creates a pyramid by:
-
Calculating spaces:
$num = 2 * $val - 2determines initial spacing -
Outer loop: Controls the number of rows (
$val) - First inner loop: Prints spaces for centering the pyramid
- Second inner loop: Prints asterisks for each row (incrementing by 1 each time)
Alternative Pattern
You can also create a solid pyramid without spaces between asterisks −
<?php
function solid_pyramid($rows)
{
for ($i = 1; $i <= $rows; $i++)
{
// Print spaces
for ($j = 1; $j <= $rows - $i; $j++)
{
echo " ";
}
// Print asterisks
for ($k = 1; $k <= (2 * $i - 1); $k++)
{
echo "*";
}
echo "<br>";
}
}
solid_pyramid(5);
?>
*
***
*****
*******
*********
Conclusion
PHP pyramid patterns use nested loops to control spacing and asterisk placement. The key is calculating proper spacing and incrementing the number of asterisks per row to create the pyramid shape.
Advertisements
