PHP For loops

The for loop statement

The for statement is used when you know how many times you want to execute a statement or a block of statements.

Syntax:

The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.

Example

The following example makes five iterations and changes the assigned value of two variables on each pass of the loop:

This will produce following result:

The foreach loop statement

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax:

Example

Try out following example to list out the values of an array.

This will produce following result:

<< PRIVOUS

NEXT >>

© 2015-16 All Rights Reserved Tech9schools