Home  >  Article  >  Daily Programming  >  PHP uses for loop to output triangles

PHP uses for loop to output triangles

藏色散人
藏色散人Original
2019-01-19 13:30:5115475browse


# During the PHP interview process, the basic knowledge test points about for loops are essential. For example, the shape of the output triangle is constructed through a for loop. Then to achieve the triangle effect, we need to use the idea of ​​nested for loops.

PHP uses for loop to output triangles

#Now we will give you a simple code example to introduce the method of PHP nested for loop to output triangles.

The code example is as follows:

<?php
for($x=1;$x<=5;$x++)
{
    for ($y=1;$y<=$x;$y++)
    {
        echo "*";
        if($y< $x)
        {
            echo " ";
        }
    }
    echo "<br>";
}

The effect is as shown in the figure below:

PHP uses for loop to output triangles

In the above code, we use two for loops, The first for loop is used to loop out the number of rows that make up the triangle. The second for loop is to loop out the number of columns.

Note: The for loop is a relatively complex loop structure in PHP. Its behavior is similar to that of C language.

The syntax of a for loop is:

for (expr1; expr2; expr3)
    statement

The first expression (expr1) is unconditionally evaluated (and executed) once before the loop starts.

expr2 is evaluated before each loop. If the value is TRUE, the loop continues and the nested loop statement is executed. If the value is FALSE, the loop is terminated.

expr3 is evaluated (and executed) after each loop.

Each expression can be empty or include multiple expressions separated by commas. In the expression expr2, all comma-separated expressions are evaluated, but only the last result is taken. Empty expr2 means that the loop will continue indefinitely (like C, PHP implicitly assumes that its value is TRUE). This may not be as useless as you think, since you often want to end a loop with a conditional break statement rather than truth-checking a for expression.

This article is an introduction to the method of outputting triangles in PHP for loop. It is very simple and easy to understand. I hope it will be helpful to friends in need!


The above is the detailed content of PHP uses for loop to output triangles. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn