September 23, 2018

How to draw different type of pyramid in PHP using short code?



To draw a simple pyramid:
Example:

<pre>
<?php
 $no = $i = 5;
 while ($i--)
    echo str_repeat(' ', $i).str_repeat('*', $no - $i)."\n";
?>
</pre>

Output:

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

Note: If you want display in middle like below

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

- You need just give space after start in while loop in ablove example like:
Example:
<pre>
<?php
 $no = $i = 5;
 while ($i--)
    echo str_repeat(' ', $i).str_repeat('* ', $no - $i)."\n";
?>
</pre>


- The next example for display below pyramid:
Example:

<?php
$num=1;
for($i=1;$i<5;$i++){
   for($j=1;$j<=$i;$j++){
       echo $num;
       $num=$num+1;
   }
   echo "<br />";
}
?>

Output:
1
23
456
78910

No comments:

Post a Comment

Integrating Google reCAPTCHA v3 in HTML Form with PHP

  What is Google reCAPTCHA v3? Google reCAPTCHA is a free service that helps protect websites from spam and abuse. reCAPTCHA v3 is the lates...