PHP函数功能创造菱形

通过后台验证后记得点右上角的采纳~~ 还有这个问题:https://ask.csdn.net/questions/7426541?spm=1001.2014.3001.5505

<?php
function rhombus($n=10){
  $arr=array();
  $half=ceil($n/2);
  for ($i = 0; $i < $half; $i++)
  {
     $arr[$i]="";
     $num=$half + $i + 1;
     $start=$half - $i;
     for ($j = 1; $j <$num ; $j++){
        if ($j < $start)  $arr[$i].="-";
        else{
          $arr[$i].=($j==$start||$j==$num-1)?"*":"-";  
        }
     }
  }
  $s="";
  for($i=0;$i<count($arr);$i++)$s.=$arr[$i]."<br>";
  for($i=count($arr)-1;$i>=0;$i--)$s.=$arr[$i].($i==0?"":"<br>");
 
  return $s;
}
$rhombus_str=rhombus();
echo $rhombus_str;
 
?>

 

改成更不用数组的了。。~ 

<?php
function rhombus($half=5){;
  $s1="";
  $s2="";
  for ($i = 0; $i < $half; $i++){
     $num=$half + $i + 1;
     $start=$half - $i;
     for ($j = 1; $j <$num ; $j++){
        if ($j < $start)  $s1.="-";
        else{
          $s1.=($j==$start||$j==$num-1)?"*":"-";  
        }
     }
     $s1.="<br>";
  }
  
  for ($i = $half-1; $i>=0; $i--){
     $num=$half + $i + 1;
     $start=$half - $i;
     for ($j = 1; $j <$num ; $j++){
        if ($j < $start)  $s2.="-";
        else{
          $s2.=($j==$start||$j==$num-1)?"*":"-";  
        }
     }
       $s2.=($i==0?"":"<br>");
  }

 
  return $s1.$s2;
}
$rhombus_str=rhombus();
echo $rhombus_str;
 
?>