Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Repetition(Iteration) Control Structures

The while Construct

The while construct tells PHP to execute a block of code over and over... for as long as the test expression evaluates to TRUE. The sytax for the while construct is:

while(test expression){
			PHP Statement 1;
			PHP Statement 2;
			...
}

The value of the test expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

A example of how this can be used is to print all elements in an array:

$arrayLength = sizeof($fruits);
while($counter < $arrayLength){
	print $fruits[$counter];
	$counter++;
}

Let's explain the code. We first make use of the array function sizeof() to get the number of items ('rooms' if you still remember) in a array (our array is $fruits from the previous lesson).

Once we figure that out, we print the contents of the first item $fruits[$counter]. When starting, $counter is 0 because we have not (thus far) assigned anything to $counter. It is only them that we increment the value of $counter by 1, print the contents of $fruits[$counter] ($counter is now 1), increment is by 1, (now $counter is 2).... until we have traversed the entire array.

If you remember, we said that the statement block within the while may not execute even once if the test expression is false by the time PHP gets to the while. This could be a limitation. To solve this problem, we use a do... while construct

<< Repetition(Iteration) Control Structures | The do... while Iteration Construct >>

JamHitz Productions