Php output pyramid two methods

Source: Internet
Author: User

User-defined function implementation pyramid

The code is as follows: Copy code
<? 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 and 20
* $ Sort indicates sorting. true indicates positive Order. FALSE indicates reverse order.
*/
Function fun_py ($ rows = 9, $ sort = true ){
If ($ rows <1 | $ rows> 20 ){
Return "must be between 1 and 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. = '& nbsp ';
     }
    }
$ Str. = '*'. '& nbsp ';
   }
  }
} 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. = '& nbsp ';
     }
    }
$ Str. = '*'. '& nbsp ';
   }
  }
 }
Return $ str;
}
Echo fun_py (9, false );
?>


Next we will implement a pyramid shape object, and we also use the for loop.

The code is as follows: Copy code

<? Php
/**
Pyramid forward
**/
For ($ a = 1; $ a <= 10; $ a ++ ){
For ($ B = 10; $ B >=$ a; $ B --){
Echo "& nbsp ";
  }
For ($ c = 1; $ c <= $ B; $ c ++ ){
Echo "*". "& nbsp ";
 }
Echo "<br/> ";
}
?>

I also want to put this pyramid upside down.

The code is as follows: Copy code

<? Php
/**
Inverted pyramid
**/
For ($ a = 10; $ a >=1; $ --){
For ($ B = 10; $ B >=$ a; $ B --){
Echo "& nbsp ";
  }
For ($ c = 1; $ c <= $ B; $ c ++ ){
Echo "*". "& nbsp ";
 }
Echo "<br/> ";
}
?>

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.