Computers, Programming
The for loop in PHP
One of the main tasks of computers is the processing of large amounts of data, in humans, this occupation would require a very large expenditure of time. To perform complex treatments, cycles were invented. Consider the for loop. It happens that it is necessary to repeat some of the pieces of code a certain number of times, and then the cycles come to the rescue. The for loop is one of the most popular.
Operators that are often used in the for loop
First, let's look at a group of operators that are often used in loops. They are called an increment and decrement. The increment operator is written with two pluses (++), it increments by one. Decrement, on the contrary, reduces the value by 1, denoted by its two minuses (-). These operators are used as a counter. If PRE-decrement / increment is used, the variable decreases / increases, and then this value is used. In POST-decrement / increment, the variable is first used, and only then is it reduced or increased.
Syntax
The for loop executes the execution of the instruction block as long as the specified condition is true. In other words, this is a set of commands that is repeated, until the specified condition is fulfilled.
It is believed that the for loop is one of the hardest in PHP. Its syntax is this:
For (part_1; part_2; part_3)
{Code;}
Particularly interesting is what is inside the parentheses. As you can see, there are three parts. They are separated by a semicolon. Where PHP part1 does what it says. If there is an expression, then it is executed. As a rule, there is a counter involved. In part 2 there is an if, then it is checked whether the fact that in part 1, if yes (true), is true, PHP executes the code that is inside the braces. In part three, the counter increases or decreases.
Consider the for php loop by example
Problem
We will perform a small task. There is some suggestion: "Hello people!" It is necessary to deduce this phrase vertically. How it's done?
We need a for loop to solve the set task. We recall the function strlen (), which returns the length of the line.
If the string is static, use other options.
In the second variant, everything is left in the for loop.
Using the for loop in PHP, you can solve many problems!
Similar articles
Trending Now