Program that prints star pattern I have a program that prints the star pattern. 

Starr Pattern is:

          * 
          * 
          * 
          * 
  * * * * * * * * * 
          * 
          * 
          * 
          * 


My code is:

$n=5;

for($i=0; $i&lt;$n; $i++){

  for($k=$n-$i; $k&gt;0; $k--){
      echo ' '.' ';
  }
  for($j=0; $j&lt; ($tot = $i+1); $j++){

      if($i==$j &amp;&amp; $tot&lt;$n){
        echo '* ';
      }else{
          if($tot&lt;$n){
            echo ' '.' ';  
          }else{
             echo '* ';
          }
      }


  }

  if($i == ($n-1)){
      for($l=$n-1; $l&gt;0;$l--){
         echo '* ';      
       }
     }  
  echo '&lt;br/&gt;';

}

for($i=0;$i&lt;$n;$i++){
  for($k=$n-$i; $k&gt;0; $k--){
      echo ' '.' ';
  }

  for($j=0; $j&lt; ($tot = $i+1); $j++){

      if($i==$j &amp;&amp; $tot&lt;$n){
        echo '* ';
            }else{
              echo ' '.' '; 
            }
    }
  echo '&lt;br/&gt;';
}


My question is that how can I calculate the complexity of this code?

And also Is there a good way to reduce loops?
It looks nice. Can you please make me understand how it works


For example

 function f($n){$s='';$b=str_pad('*',($m=$n*2+1),' ',2);for($i=0;$i&lt;$m;++$i)$s.=($i==$n)?str_repeat('*',$m):$b;return chunk_split($s, $m);}


Output

     *     
     *     
     *     
     *     
     *     
***********
     *     
     *     
     *     
     *  


Sandbox

Let me write it in a way that is easier to see

$n = 5;
$row_len = $n*2+1;
$output = '';
//pad $n spaces on each side of *
$default = str_pad('*',$row_len,' ',STR_PAD_BOTH); //is = "     *     "

//loop once for each vertical row (same as width)
for($i=0;$i&lt;$row_len;++$i){
    if($i==$n){
        //do the center line all *'s
        $output .= str_repeat('*',$row_len);//is = "***********"
    }else{
        //use the default line from above
        $output .= $default;
    }
}

//now we have a single line that is the length squared so we can chunk it
//into equal parts, to make a square
echo chunk_split($output, $row_len);  //is = "     *          *     ***********"


Sandbox

Basically we can create the "     *       " row by using string pad.  Because we can pad spaces on both sides of a * up to the length of a row  ($n*2)+1.

Then the center row, is just * so we can use string repeat to the length of the row for that line.

Last we take our big huge line of spaces and * and split it into chunks (\n) on the length of our row we want.