php prints a solid and hollow rhombus with side length N
Solid rhombus calculation method:
$n: side length
$i: current line, starting from 0
$rows: Total number of rows
Upper
Number of preceding spaces =$n-$i-1
Number of characters =$i*2+1
Lower
Number of preceding spaces =$i-$n+1
Number of characters =($rows-$i)*2-1
Using str_pad can reduce for/while loops
/** * 打印实心菱型 * @param int $n 边长,默认5 * @param String $s 显示的字符, 默认* * @return String */ function solidDiamond($n=5, $s='*'){ $str = ''; // 计算总行数 $rows = $n*2-1; // 循环计算每行的* for($i=0; $i<$rows; $i++){ if($i<$n){ // 上部 $str .= str_pad('', ($n-$i-1), ' '). str_pad('', $i*2+1, $s)."\r\n"; }else{ // 下部 $str .= str_pad('', ($i-$n+1), ' '). str_pad('', ($rows-$i)*2-1, $s). "\r\n"; } } return $str; } echo '<xmp>'; echo solidDiamond(5); echo '</xmp>';
* *** ***** ******* ********* ******* ***** *** *
/** * 打印空心菱型 * @param int $n 边长,默认5 * @param String $s 显示的字符, 默认* * @return String */ function hollowDiamond($n=5, $s='*'){ $str = ''; // 计算总行数 $rows = $n*2-1; // 循环计算每行的* for($i=0; $i<$rows; $i++){ if($i<$n){ // 上部 $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{ // 下部 $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>';
* * * * * * * * * * * * * * * *
The above introduces PHP to print a solid and hollow diamond shape with side length N, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.