PHP output pyramid 2 ways to implement, PHP output pyramid 2
This article describes 2 implementations of the PHP output pyramid. Share to everyone for your reference. The specific analysis is as follows:
Here are a summary of 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 used in the former is only a higher level.
The custom function implements the pyramid with the following code:
Copy CodeThe code is 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 sort true to indicate positive order false for reverse
*/
function Fun_py ($rows = 9, $sort =true) {
if ($rows <1 | | $rows >20) {
Return "must be between 1-20";
}
if ($rows! = (int) ($rows)) {
Return ' line number 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);
?>
The following is the implementation of a pyramid shape, the general use of the For loop, the code is as follows:
Copy CodeThe code is 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 "
";
}
?>
Also want to make the pyramid stand upside down, the code is as follows:
Copy CodeThe code is 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 "
";
}
?>
I hope this article is helpful to everyone's PHP programming.
http://www.bkjia.com/PHPjc/928224.html www.bkjia.com true http://www.bkjia.com/PHPjc/928224.html techarticle PHP Output Pyramid 2 Implementation methods, PHP output pyramid 2 Examples of this article describes the PHP output pyramid 2 ways to implement. Share to everyone for your reference. The specific analysis is as follows: ...