2 ways to implement PHP output pyramid, 2 types of PHP output pyramid_PHP tutorial

WBOY
Release: 2016-07-13 10:11:39
Original
1208 people have browsed it

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.

www.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...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!