Home > Backend Development > PHP Tutorial > What are the loop statements in php

What are the loop statements in php

下次还敢
Release: 2024-04-29 12:57:16
Original
1258 people have browsed it

The following loop statements are provided in PHP: while: Repeat the code block when the condition is true. do-while: Execute the code block first, then check whether the condition is true, and continue executing the loop if it is true. for: Initialize the variable, check the condition, execute the code block, and then increment the variable. foreach (array): Loops through the elements in the array and provides the key and value. foreach (object): Loops through the properties in the object and provides property names and values.

What are the loop statements in php

Loop statements in PHP

PHP provides a variety of loop statements that are used to perform loop statements when certain conditions are met. block of code is executed repeatedly. These loop statements include:

while loop

  • Syntax: while (condition)
  • Repeatedly execute the code block , as long as the condition is true.

do-while loop

  • Syntax: do {...} while (condition);
  • Execute the code block first, then check whether the condition is true, and if it is true, continue to execute the loop.

for loop

  • Syntax: for (initialization; condition; increment)
  • Initialize variables , checks the condition, executes the code block, and then increments the variable.

foreach loop

  • Syntax: foreach ($array as $key => $value)
  • Loop through the elements in the array, providing keys and values ​​as needed.

foreach loop (object)

  • Syntax: foreach ($object as $property => $value)
  • Loop through the properties in the object and provide property names and values ​​as needed.

break statement

  • is used to exit immediately from the loop.

continue statement

  • is used to skip the current iteration of the loop and continue executing the next iteration.

Example:

<code class="php">// while 循环
$i = 0;
while ($i < 10) {
    echo $i . "\n";
    $i++;
}

// for 循环
for ($i = 0; $i < 10; $i++) {
    echo $i . "\n";
}

// foreach 循环(数组)
$array = ['foo', 'bar', 'baz'];
foreach ($array as $item) {
    echo $item . "\n";
}</code>
Copy after login

The above is the detailed content of What are the loop statements in php. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template