YouTip LogoYouTip

Php Looping For

```html PHP For Loop
Home > HTML > CSS > JS > Local Bookmarks > Search
Vue3 Tutorial Vue2 Tutorial
Bootstrap3 Bootstrap4 Bootstrap5
Machine Learning PyTorch TensorFlow Sklearn NLP AI Agent Ollama Coding Plan

PHP Tutorial

PHP Forms

PHP Advanced

PHP 7 New Features

PHP Database

PHP For Loop

< Previous Next >

PHP For Loop

Loops execute a block of code a specified number of times, or until a certain condition is met.

PHP Loops

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal line of codes in a script, we can use loops to perform a task like this.

In PHP, we have the following looping statements:

  • while - loops through a block of code as long as the specified condition is true
  • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array

The following sections will explain and show examples of each loop type.

PHP For Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (init counter; test counter; increment counter) {
    code to be executed;
}

Parameters:

  • init counter: Initialize the loop counter value
  • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment counter: Increases the loop counter value

Example

The example below defines a loop that starts with $i = 1. The loop will continue to run as long as $i is less than or equal to 5. $i will increase by 1 each time the loop runs:

<?php
for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";
}
?>

PHP foreach Loop

The foreach loop is used to loop through arrays.

Syntax

foreach ($array as $value) {
    code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Example

The following example demonstrates a loop that will print the values of the given array:

<?php
$colors = array("red","green","blue","yellow");

foreach ($colors as $value) {
    echo "$value <br>";
}
?>

< Previous: PHP While Loop Next: PHP Functions >

Online Execution Tool

Use Online SQL Execution Tool to execute SQL commands in your browser.

Recommend:

- Learn Not Just Technology, But Also Dreams!

Copyright Β© 2025 Runoon.com All Rights Reserved.

```
← Php FunctionsPhp Looping β†’