Pyramid Graphics Realized by Loop in PHP

  • 2021-07-26 07:13:46
  • OfStack

Today, I learned the most basic PHP conditions and circular statements. Finally, the teacher raised several questions, one of which is fun to realize the hollow pyramid image.

What the teacher wants us to achieve is:

*

* *

The hollow pyramid of * * *.

Type 1:


for ($i=1;$i<=5;$i++){
        switch ($i){
            case 1:
                echo "  "."*"."  ";
                break;
            case 2:
                echo "     ";
                break;
            case 3:
                echo " "."*"." "."*"." ";
                break;
            case 4:
                echo "     ";
                break;
            case 5:
                echo "*"." "."*"." "."*";
                break; 
        }
    echo "<br>";

The realization effect is the image required by the teacher, but the teacher thinks that there should be a simpler way to realize it, which can output the space and * separately;

So there is the second kind:


for($a=0;$a<4;$a++){
        for($b=4;$b>$a;$b--){
            echo " ";
        }
        for($c=1;$c<=$a;$c++){
            echo "*";
        }
        for($d=0;$d<=$a;$d++){
            echo "*";
        }
        echo "<br>";
    }

The effect of this implementation is not as hollow as that just now, and the effect is as follows:

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

This has not yet achieved hollow, try again later, today's first blog is completed, I hope that the future can be written long.


Related articles: