All Syllabus

Home About PHP HTML CSS SQL Java Script jQuery AJAX      

PHP Tutorial

PHP Introduction

PHP 5 Installation

PHP 5 Syntax

PHP 5 Variables

PHP 5 echo and print Statements

PHP 5 Data Types

PHP 5 String Functions

PHP 5 Constants

PHP Arithmetic Operators

PHP 5 if...else...elseif Statements

PHP 5 switch Statement

PHP 5 while Loops

PHP 5 for Loops

PHP 5 Functions

PHP 5 Arrays

PHP 5 Sorting Arrays

PHP 5 Superglobals

PHP Forms

PHP 5 Form Handling

PHP 5 Form Validation

PHP 5 Forms - Required Fields

PHP 5 Forms E-mail /URL

PHP Form Complete

PHP Advanced

PHP 5 Multidimensional Arrays

PHP 5 Date and Time

PHP Include Files

PHP File Handling

PHP File Open/Read

PHP File Create/Write

PHP File Upload

PHP Cookies

PHP Sessions

PHP E-mail

PHP Secure E-mails

PHP Error Handling

PHP Exception Handling

PHP Filter

PHP Database

PHP MySQL Introduction

PHP MySQL Connect

PHP Create DB/Tables

PHP MySQL Insert Into

PHP MySQL Select


PHP Order By

PHP Update

PHP Delete



PHP 5 for Loops

PHP for loops execute a block of code a specified number of times.

The PHP for Loop

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


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


  • 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

The example below displays the numbers from 0 to 10:


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


The PHP foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.


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.

The following example demonstrates a loop that will output the values of the given array ($colors):


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

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