Arrays go naturally with for loops. Very often when you have an array variable, you step through all of its values and do something to each one. In this example, I want to print the index and the corresponding country’s name. Here’s the for loop that performs this task:
Because I know the array indices will vary between 1 and 5, I set up my loop so the value of $i will go from 1 to 5. Inside the loop, I simply print the index ($i) and the corresponding country ($camelPop[$i]). The first time through the loop, $i is 1, so $camelPop[$i] is $camelPop[1], which is Somalia. Each time through the loop, the value of $i is incremented, so eventually every array element is displayed.
The advantage of combining loops and arrays is convenience. If you want to do something with each element of an array, you only have to write the code one time, then put that code inside a loop. This is especially powerful when you start designing programs that work with large amounts of data. If, for example, I want to list the camel population of every country in the UN database rather than simply the top five countries, all I have to do is make a bigger array and modify the for loop.
for ($i = 1; $i <= 5; $i++){
print "$i: $camelPop[$i]<br />\n";
} // end for loop
print "$i: $camelPop[$i]<br />\n";
} // end for loop
The advantage of combining loops and arrays is convenience. If you want to do something with each element of an array, you only have to write the code one time, then put that code inside a loop. This is especially powerful when you start designing programs that work with large amounts of data. If, for example, I want to list the camel population of every country in the UN database rather than simply the top five countries, all I have to do is make a bigger array and modify the for loop.
Comment