In this article we will learn how to print patterns. The star triangle in PHP is made using for loop and foreach loop. There are a lot of star patterns. We'll show some of them here.
1: Pyramid Star Simple Pattern in PHP
Create a simple star pattern using PHP For loop , you have to use two PHP for loop. Due to this, nested for loop define rows to create with the columns of stars.
You are almost done with the addition of this to the below code.
<?php
for($a=0;$a<=5;$a++){
for($k=0;$k<=$a;$k++){
echo "*";
}
echo "<br/>";
}
?>
The first for loop define the number of rows for the simple pattern. The second loop print each row with the star symbols.
Out Put
*
**
***
****
*****
******
2: Decreasing number of stars PHP
<?php
for($i=0;$i<=5;$i++){
for($j=5-$i;$j>=0;$j--){
echo "*";
}
echo "<br>";
}
?>
Out Put
******
*****
****
***
**
*
3: Triangle Pyramid Star Pattern in PHP
<?php
//Define Pyramid Row hight
$size = 5;
for($i=1;$i<=$size;$i++){
for($j=1;$j<=$size-$i;$j++){
echo " ";
}
for($k=1;$k<=$i;$k++){
echo "* ";
}
echo "<br />";
}
?>
Out Put
*
* *
* * *
* * * *
* * * * *
4: Half Pyramid Pattern using alphabets in PHP
$start_alphabet = 'A';
$stop_alphabet = 'E'; // add your alphabet as stop alphabet
$key = (ord($stop_alphabet) - ord($start_alphabet)) + 1;
for($i=1; $i <= $key; ++$i)
{
for($j=1;$j<=$i;++$j)
{
echo ($start_alphabet." "); //add space in alphabet
}
++$start_alphabet;
echo ("<br>"); // brake line
}
Out Put
A
B B
C C C
D D D D
E E E E E
5: Print pyramid using numbers in PHP
$key = $count = $count_temp = 0;
$rows = 5; // add your number of row
for($index = 1; $index <= $rows; ++$index){
for($space=1; $space <= $rows - $index; ++$space){
echo (" "); //add space
++$count;
}
while($key != 2 * $index-1){
if ($count <= $rows-1){
echo ($index + $key." "); //add space in numbers
++$count;
}else{
++$count_temp;
echo ($index + $key-2 * $count_temp." "); //add space in numbers
}
++$key;
}
$count_temp = $count = $key = 0;
echo ("<br>"); // brake line
}
Out Put
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5