Home > Article > Backend Development > About PHP loops - Detailed explanation of For loop
This article will provide a detailed understanding of the relevant knowledge of php loops and Buddhafor loops.
for loop
The for loop is used when you know in advance the number of times the script needs to run.
Syntax
for (initial value; condition; increment){
Code to be executed;}
Parameters:
Initial value: Mainly initializes a variable value, used to set a counter (but can be any code that is executed once at the beginning of the loop).
Conditions: Restrictions on loop execution. If TRUE, the loop continues. If FALSE, the loop ends.
Increment: Mainly used to increment the counter (but can be any code that is executed at the end of the loop).
Note: The above initial value and increment parameters can be empty, or have multiple expressions (separated by commas).
Example
The following example defines a loop with an initial value of i=1. As long as the variable i is less than or equal to 5, the loop will continue to run. Each time the loop runs, the variable i will be incremented by 1:
Instance
<?phpfor ($i=1; $i<=5; $i++){ echo "The number is " . $i . "<br>";}?>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
foreach Loop
foreach loop is used to traverse the array.
Syntax
foreach ($array as $value){ 要执行代码;}
Every time you perform a loop, the value of the current array element will be assigned to the $value variable (the array pointer will move one by one). When you perform the next loop, you will See the next value in the array.
Example
The following example demonstratesa loop that outputs the values of a given array:
Example
<?php$x=array("one","two","three");foreach ($x as $value){ echo $value . "<br>";}?>
Output:
one
two
three
This article explains the usage of loop statements in detail. For more learning materials, please pay attention to the php Chinese website.
Related recommendations:
About the operation of PHP If...Else statement
About PHP 5 data types Related explanation
PHP MySQL operation and method of reading data
The above is the detailed content of About PHP loops - Detailed explanation of For loop. For more information, please follow other related articles on the PHP Chinese website!