About PHP loops - Detailed explanation of For loop

jacklove
Release: 2023-03-25 14:50:02
Original
2351 people have browsed it

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>";}?>
Copy after login

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){
    要执行代码;}
Copy after login

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>";}?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!