So why do we use loops? There are hundreds and hundreds of reasons, the widest usage is probably to cycle through values of some sort of data. For example, you might be writing a messaging system in PHP, which would allow users of your website to send private messages to each other once they register. You would write a MySQL query which would pull all the user's letter from the database. To show all the letters you would use a loop to show all the rows of the query (all the separate messages) on a page.
To create a loop you need to add some rules which will dictate how the loop should behave. Usually we need to give three values, the starting value of the counter (which tells the loop how many times it has executed), an ending value (which tells the script to stop looping if it is reached) and an increment, which deals with changing the starting counter value in some way (so that it eventually reaches the end value, hence ending the loop).
Let's take a look at an example to clear things up. I will create an array, the members of this array will contain the names of some of my friends. To echo these variables I would normally have to separately echo them, which would result in many extra lines, especially if there are many names. To get around this problem I will accomplish this with a looő. Here's the code in full, with a detailed explanation below.
$friends = array('Paul', 'Martin', 'Greg', 'Viki', 'Andrew');
$num = count($friends);
for ($i = 0; $i < $num; $i++)
First of all, I designated my friends. The array '$friends' holds the names of my friends. The actual names can be referenced using index numbers. '$friends' would be Paul, '$friends' would be Greg. As you can see the first value is referenced with the index '0', this is important to keep in mind.
The second row simply counts how many names are stored in the array. This may seem redundant since I wrote the names right? I should know how many there are! Well in this simple case it's true, however, if I count it with PHP as opposed to just writing "5" (later on in the loop) I need to modify the code in two places if I add a name to the list. Also, if the names are pulled from a database of users I can't go changing the total count whenever someone registers right? I probably don't even know it anyway.
Everything following is part of the loop. This is a for loop, the simplest kind (we'll get into some others in a later post), the first line of the loop designates that this is a for loop, and inputs the three bits of info we need (separated by semicolons). The first bit creates variable named '$i' and assigns it the value 0. This will be the starting value for our counter. The second bit of information specifies how long the loop should execute. In this case it is set up so the script should execute until "$i" is less than "$num", or the total number of names in this case. The last bit of information tells the loop to increment the "$i" each time a loop is executed. "++" is a PHP operator, it's a way of telling the script to add 1 to the variable in question, I could also have written "$i + 1".
Now you know that each time a loop executes 1 is added to "$i". So on the first go "$i" has a value of 0. Once the loop has executed the value increases, so on the second pass "$i" equals 1. On the fifth pass, "$i" will be equal to 4. Since we have set the loop to run until the value if '$i' is less than the number of names it will now stop. If it would execute again "$i" would be five, which equals "$num", as opposed to being smaller than it.
Now that we understand the value of "$i", all that's left is the code between the parenthesis. Anything between gets run in the loop, so everything will be done as many times as the loop runs. The first line will echo the name of the person, the second just ads a line break afterward so we get a nice, neat list, one under the other.
As you can see the name in question is referenced using "$i". Since the index of the names ranges from 0 to 5 (or as many names as there are), and "$i" is also incremented by one, starting from 0, it is very convenient to simply use "$i" to reference which name we want to echo. On the first pass "$i" is 0 and indeed we want to echo "$friends".
This is the reason that the starting value for the counter is 0 as opposed to 1. Since the array index also starts at 0, it is easier to make them same from the start, as opposed to modifying the array keys for example.
That's it for the basics of looping, there are many tips and tricks you can use, and other modes of looping, we will get there soon though! I tried to explain in as much detail as possible, which I will not be repeating in future loop articles, so I'll direct you here for basics. If you don't understand something, feel free to ask in the comments.Advertisement
Advertising revenue is falling fast across the Internet, and independently-run sites like Ghacks are hit hardest by it. The advertising model in its current form is coming to an end, and we have to find other ways to continue operating this site.
We are committed to keeping our content free and independent, which means no paywalls, no sponsored posts, no annoying ad formats or subscription fees.
If you like our content, and would like to help, please consider making a contribution:
Ghacks is a technology news blog that was founded in 2005 by Martin Brinkmann. It has since then become one of the most popular tech news sites on the Internet with five authors and regular contributions from freelance writers.