Any loop allows you to run some code over and over again. FOR loops run for a set number of times.
Open the arraysandloops.php page you just created in your editor.
After the existing PHP code (just after the PRE, PRINT_R, PRE lines) add this loop:
echo "<p>The four names were";
for ($i=0; $i<=3;$i=$i+1) {
echo " $names[$i]";
}
echo ".</p>";
There is a lot of new stuff in that loop:
- the first line is not new and creates the first part of the HTML paragraph
- the loop structure is similar to an IF statement with a condition in brackets and braces to hold the actions
- the condition is more complex and has three parts separated by semi-colons:
- first the value of a variable is set to zero (it will be used as the counter)
- then the condition itself (which here says that $i must be less than or equal to (<=) 3
- the final bit says that $i should be incremented (1 added to it) each time around the loop
- the next line has the array in an ECHO statement, the array is inside quotes to allow the space at the beginning to be ECHOed to separate the results
- the loop will run four times (with $i being 0, 1, 2 and then 3) and then when $i is 4 the condition fails and the loop stops
- after the loop stops the final line finishes off the sentence and closes the P tag.
Save the file and upload it. It should echo all four names to the Web page. Look at the source. Fiddle with the code until you understand how a FOR loop works.



