This article illustrates a method for PHP to print a solid and hollow shape with a side length of N. Share to everyone for your reference. The specific analysis is as follows:
Solid Diamond Type calculation method:
$n: Side length
$i: Current line, 0 start
$rows: Total Rows
Upper
Number of spaces before = $n-$i-1
Number of characters = $i *2+1
Lower
Number of spaces before = $i-$n +1
Number of characters = ($rows-$i) *2-1
Using Str_pad can reduce loops such as For/while
Copy Code code as follows:
/**
* Print solid Diamond type
* @param int $n side length, default 5
* @param string $s display character, default *
* @return String
*/
function Soliddiamond ($n =5, $s = ' * ') {
$str = ';
Calculate total number of rows
$rows = $n *2-1;
Loops calculate the * of each line
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 ' <xmp> ';
Echo Soliddiamond (5);
Echo ' </xmp> ';
Copy Code code as follows:
*
***
*****
*******
*********
*******
*****
***
*
The calculation method of hollow-type diamond:
$n: Side length
$i: Current line, 0 start
$rows: Total Rows
Upper
Number of spaces before = $n-$i-1
Number of empty spaces = $i *2+1-2
Number of characters = $i *2+1-Empty spaces
Lower
Number of spaces before = $i-$n +1
Number of white spaces = ($rows-$i) *2-1-2
Number of characters = ($rows-$i) *2-1-Empty spaces
Copy Code code as follows:
/**
* Print Hollow Rhombus type
* @param int $n side length, default 5
* @param string $s display character, default *
* @return String
*/
function Hollowdiamond ($n =5, $s = ' * ') {
$str = ';
Calculate total number of rows
$rows = $n *2-1;
Loops calculate the * of each line
for ($i =0; $i < $rows; $i + +) {
if ($i < $n) {//Upper
$tmp = $i *2+1;
$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 ' <xmp> ';
Echo Hollowdiamond (5);
Echo ' </xmp> ';
Copy Code code as follows:
*
* *
* *
* *
* *
* *
* *
* *
*
I hope this article will help you with your PHP program design.