This article illustrates 2 implementations of the PHP output pyramid. Share to everyone for your reference. The specific analysis is as follows:
Here is a summary of the two ways to achieve pyramid printing, one is the use of custom functions, the other is the use of the For loop, in fact, both have been used only a higher number of the former.
The custom function implements the pyramid with the following code:
Copy Code code as follows:
<?php
/**
* Pyramid
* String fun_py (int $rows = 9, bool $sort =true)
* $rows indicates that the number of rows must be an integer and must be between 1-20
* $sort indicates that sort true indicates positive sequence false to reverse
*/
function Fun_py ($rows = 9, $sort =true) {
if ($rows <1 | | $rows >20) {
Return "must be between 1-20";
}
if ($rows!= (int) ($rows)) {
Return ' number of rows must be an integer ';
}
$str = "";
if ($sort) {
for ($i =1; $i <= $rows; $i + +) {
$str. = ' <br/> ';
for ($j =1; $j <= $i; $j + +) {
if ($j ==1) {
For ($k =1 $k <= ($rows-$i); $k + +) {
$str. = ';
}
}
$str. = ' * '. ';
}
}
} else{
for ($i = $rows; $i >=1; $i-) {
$str. = ' <br/> ';
for ($j =1; $j <= $i; $j + +) {
if ($j ==1) {
For ($k =1 $k <= ($rows-$i); $k + +) {
$str. = ';
}
}
$str. = ' * '. ';
}
}
}
return $str;
}
echo fun_py (9,false);
?>
The next implementation of the pyramid shape, general also used for the loop, the code is as follows:
Copy Code code as follows:
<?php
/**
Pyramid Positive Sequence
**/
For ($a =1 $a <=10; $a + +) {
for ($b =10; $b >= $a; $b-) {
echo "";
}
for ($c =1; $c <= $b; $c + +) {
echo "*". " ";
}
echo "<br/>";
}
?>
Also want to get this pyramid upside down, the code is as follows:
Copy Code code as follows:
<?php
/**
Pyramid Play Handstand
**/
For ($a =10 $a >=1; $a-) {
for ($b =10; $b >= $a; $b-) {
echo "";
}
for ($c =1; $c <= $b; $c + +) {
echo "*". " ";
}
echo "<br/>";
}
?>
I hope this article will help you with your PHP program design.