2 ways to implement PHP output pyramid _php Tips

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.