Two ways to implement PHP output pyramid, two ways of PHP output pyramid
The examples in this article describe two implementation methods of PHP output pyramid. Share it with everyone for your reference. The specific analysis is as follows:
The following summarizes two methods for implementing pyramid printing. One is to use a custom function, and the other is to use a for loop. In fact, both are used, but the former is more advanced.
Custom function to implement pyramid, the code is as follows:
Copy code The code is as follows:
/**
* Pyramid
* string fun_py(int $rows = 9, bool $sort=true)
* $rows represents the number of rows and must be an integer and must be between 1-20
* $sort means sorting true means forward order FALSE means reverse order
*/
function fun_py($rows = 9, $sort=true){
if ($rows<1 || $rows>20){
Return "Must be between 1-20";
}
if($rows!=(int)($rows)){
Return 'The number of rows must be an integer';
}
$str="";
if($sort){
for($i=1;$i<=$rows;$i++){
$str.= '
';
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.= '
';
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);
?>
Next, implement a pyramid-shaped object. The for loop is generally used. The code is as follows:
Copy code The code is as follows:
/**
Pyramid sequence
**/
for($a=1;$a<=10;$a++){
for ($b=10;$b>=$a;$b--){
echo " ";
}
for ($c=1;$c<=$b;$c++){
echo "*"." ";
}
echo "
";
}
?>
I also want to make this pyramid stand upside down. The code is as follows:
Copy code The code is as follows:
/**
Pyramid playing handstand
**/
for($a=10;$a>=1;$a--){
for ($b=10;$b>=$a;$b--){
echo " ";
}
for ($c=1;$c<=$b;$c++){
echo "*"." ";
}
echo "
";
}
?>
I hope this article will be helpful to everyone’s PHP programming design.
http://www.bkjia.com/PHPjc/928224.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/928224.htmlTechArticleTwo ways to implement PHP output pyramid, two types of PHP output pyramid. This article describes the two types of PHP output pyramid. Implementation method. Share it with everyone for your reference. The specific analysis is as follows: Next...