PHP while statements

A WHILE statement allows the code to loop until a condition is met. This will not be much use to anyone who is not using databases but you will definitely need WHILE statements when you move on to MySQL.

            
$randomstrings[0]="apple";
$randomstrings[1]="six";
$randomstrings[2]="yellow";
$randomstrings[3]="car";
$randomstrings[4]="light";
$randomstrings[5]="axe";

$i=0;

while ($randomstrings[$i]!="car"){
    echo "<p>hello</p>";
    $i++;
}            
        

More meaningful examples will come up in the MySQL pages.

When using WHILE statements be careful that the loop will end eventually. For the above example if there was no "car" string the loop would go on forever. Actually the server would kill it after a time (normally 2 minutes or so).

submit to reddit Delicious Tweet