PHP Prints a solid and hollow shape with a side length of n
Calculation method for solid type of diamond:
$n: Edge Length
$i: Current line, 0 start
$rows: Total number of rows
Upper
Number of spaces in front = $n-$i-1
Number of characters = $i *2+1
Lower
Number of spaces in front = $i-$n +1
Number of characters = ($rows-$i) *2-1
Use Str_pad to reduce loops such as For/while
/** * Print solid diamond type * @param int $n edge length, default 5 * @param string $s the character displayed, default * * @return string */function soliddiamond ($n = 5, $s = ' * ') { $str = '; Calculates the total number of rows $rows = $n *2-1; Loop calculates * for ($i =0; $i < $rows, $i + +) { if ($i < $n) {//upper $str. = Str_pad (", ($n-$i-1),"). Str_pad (" , $i *2+1, $s). " \ r \ n "; } else{ //Lower $str. = Str_pad (', ($i-$n + 1), '). Str_pad (", ($rows-$i) *2-1, $s). "\ r \ n"; } } return $STR;} Echo '
&amp; #39;; Echo Soliddiamond (5); Echo &amp; #39;
';
* *** ***** **************** ******* ***** *** *
The calculation method of hollow type of diamond:
$n: Edge Length
$i: Current line, 0 start
$rows: Total number of rows
Upper
Number of spaces in front = $n-$i-1
Number of empty spaces = $i *2+1-2
Number of characters = $i *2+1-The number of empty spaces
Lower
Number of spaces in front = $i-$n +1
Number of empty spaces = ($rows-$i) *2-1-2
Number of characters = ($rows-$i) *2-1-the number of empty spaces
/** * Print Hollow type * @param int $n edge length, default 5 * @param string $s displayed characters, default * * @return string */function hollowdiamond ($n =5, $s = ' * ') { $str = '; Calculates the total number of rows $rows = $n *2-1; Loop calculates * for ($i =0; $i < $rows, $i + +) { if ($i < $n) {//upper $tmp = $i *2+1 ) per line; $str. = Str_pad (", ($n-$i-1),"). Str_pad (Str_pad (", $tmp-2," ', Str_pad_both), $tmp, $s, str_pad_both). " \ r \ n "; } else{ //Lower $tmp = ($rows-$i) *2-1; $str. = Str_pad (", ($i-$n + 1),"). Str_pad (Str_pad (", $tmp-2, '", Str_pad_both), $tmp, $s, str_pad_both). "\ r \ n"; } } return $STR;} Echo '
&amp; #39;; Echo Hollowdiamond (5); Echo &amp; #39;
';
* * * * * * ** * * * * * * * *
The above describes the PHP printing a side-length n solid and hollow type, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.