This article mainly introduces two implementation methods of the php output pyramid, involving the calling techniques of loop statements, and has some reference value for php learning, for more information about how to implement the php output pyramid, see the following example. Share it with you for your reference. The specific analysis is as follows:
The following summarizes two ways to implement Pyramid printing. one is to use a user-defined function, and the other is to use a for loop, in fact, both are used, but the former is more advanced.
User-defined function implementation pyramid. the code is as follows:
The 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 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. ='
';
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 we will implement a pyramid shape object, which also uses the for loop. the code is as follows:
The code is as follows:
<? Php
/**
Pyramid forward
**/
For ($ a = 1; $ a <= 10; $ a ++ ){
For ($ B = 10; $ B >=$ a; $ B --){
Echo "";
}
For ($ c = 1; $ c <= $ B; $ c ++ ){
Echo "*"."";
}
Echo"
";
}
?>
The code is as follows:
The code is as follows:
<? Php
/**
Inverted pyramid
**/
For ($ a = 10; $ a >=1; $ --){
For ($ B = 10; $ B >=$ a; $ B --){
Echo "";
}
For ($ c = 1; $ c <= $ B; $ c ++ ){
Echo "*"."";
}
Echo"
";
}
?>
I hope this article will help you with PHP programming.