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/> "; } ?> |