Basics of looping in PHP

Daniel Pataki
Jan 11, 2009
Updated • Dec 29, 2014
Development
|
14

Loops are an integral part of PHP, and many other programming languages for that matter, the basics covered here would apply to JavaScript as well, even the code is very similar. A loop is simply a block of code that executes multiple times, controlled either directly, by explicitly telling the script to execute "X" times, or by using a variable, telling the script to execute "as many times as the exact hour at the time of viewing" for example.

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++)
{
echo $friends[$i];
echo '<br>';
}

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[0]' would be Paul, '$friends[2]' 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[0]".

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.

Summary
Article Name
Basics of looping in PHP
Description
Loops are an integral part of PHP, and many other programming languages for that matter. The guide walks you through the basics of PHP loops.
Author
Advertisement

Previous Post: «
Next Post: «

Comments

  1. eRIZ said on January 12, 2009 at 3:20 pm
    Reply

    While loops are very popular and useful.

    Of course, while loops are better if you don’t know how many iterations you have to do (eg. SQL data fetch).

    There’s one detail: in C there are $i++ and ++$i constructions. The second is faster, strange. ;)

    Try yourself: http://pastebin.com/f525b5c27

  2. Daniel Pataki said on January 11, 2009 at 10:56 pm
    Reply

    Hi eRIZ!

    Thanks for that clarification! I actually didn’t mean it would work, I meant that it is equivalent, although I agree, I wasn’t too clear, I should have written out the proper form! I did not know it was faster though, thanks for that awesome, awesome benchmark link :)

    Hi What is PHP!

    Yes, from the article: “there are many tips and tricks you can use, and other modes of looping, we will get there soon though”

    In some cases you must (or at least it is much easier) to use while loops, if you want some rules for a specific interval in the loop. I also use foreach a lot, I will get there in due time :)

  3. What is PHP? said on January 11, 2009 at 10:47 pm
    Reply

    For loops are not the only type of loops available in PHP. While loops are very popular and useful.

  4. eRIZ said on January 11, 2009 at 9:33 pm
    Reply

    I could also have written “$i + 1″.

    Nope, because $i+1 doesn’t affect on parsed variable what $i++ does. Although the proper code should be $i = $i+1 it brings back a bad Pascal’s behaviour. PHP is C based language so use C operators which are often faster than other constructions.

    Take a look: http://www.php.lt/benchmark/phpbench.php

    A PHP performance benchmark which tests all possible array iterating methods.

  5. Daniel Pataki said on January 11, 2009 at 9:29 pm
    Reply

    Hi Angelo R.!

    Thanks for the explanation! Also, I agree, php.net is the best. I also refer to it a lot, I don’t have all those hundreds of built in functions in my head :)

    I too have the same exact keyword in firefox :) Although I know a lot of function names I don’t always know their arguments and in which order I should put them, so this is a great quick reference!

    Hi iampriteshdesai!

    Sorry, but I only cover web specific topics like HTML, CSS, PHP, MySQL, Javascript, AJAX, etc. I am not that well versed in C++, while I might be able to write the program I am not sure I could do it with best practices.

    However I will have time in February, and I am scheduling some learning time for C++ anyway, if this is still an issue for you pelase email me at daniel [at symbol] hackyourday [.dot.symbol] com

  6. Fabio said on January 11, 2009 at 9:19 pm
    Reply

    Dear Angelo.

    Thanks for helping!

  7. Angelo R. said on January 11, 2009 at 7:11 pm
    Reply

    @Fabio: Echo essentially just prints out whatever is between the tags to the browser. So if you say

    echo “Hello, World”;

    when you load the page it will print out Hello, World to your browser.

    Because of this, you can actually place HTML/Javascript/CSS tags (anything that you would use when developing a website actually) into echo tags.

    http://ca.php.net/manual/en/function.echo.php

    Since the PHP manual is so great (I find myself referring to it quite a bit) I actually set up a keyword search for it. So now, I can just type in php my_search_term and it automatically searches the website. I suggest any developers do that same, as it saves a lot of time when you’re typing not to have to switch with a mouse.

  8. Fabio said on January 11, 2009 at 6:13 pm
    Reply

    Dear Daniel! Please, could you detail me better what will the echo commando do????

    In C language, I could insert a row with “printf” and then you should got a message on the screen. But php I don’t know and even so PHP commands will interact with HTML.

    Thanks,

    Fabius

  9. iampriteshdesai said on January 11, 2009 at 6:00 pm
    Reply

    Hi Daniel!
    Will you please write an tutorial to make a simple GUI program (say a calculator) with Visual Studio C++
    I want to do GUI in C++, at college we have only done console (DOS) software.

  10. Paul. said on January 11, 2009 at 3:03 pm
    Reply

    Thanks Daniel for this christal clear artikel, again, and not to forget, your links. Please keep up the good work. And even more references to learning websites, are very welcome. And Jojo thanks for you links.

  11. Daniel Pataki said on January 11, 2009 at 12:53 pm
    Reply

    Hi Jojo!

    Thanks for those links, also W3Schools is a great palce for MANY languages, check out the site at
    http://w3schools.com

    I also like Your HTML Source at
    http://yourhtmlsource.com

    PHP actually has one of the best online manuals ever, take a look at php.net. It can be a bit daunting at first, but it’s actually written very well.
    http://php.net

  12. Jojo said on January 11, 2009 at 11:25 am
    Reply

    I used to do assembler, PL/1 and JCL systems programming years ago in mainframe systems.

    I’ve been telling myself for years that I would someday go back to programming by learning some modern languages. Now seems like I will finally begin to tackle this project.

    Here’s some links I am looking at that might be useful for others:

    The Absolute Beginner’s Guide to Programming on the Web
    http://appjet.com/learn-to-program/lessons/intro

    http://www.thefreecountry.com/

    http://www.freetechbooks.com/

    http://jennifermadden.com/index.html (Javascript tutorial)

    Microsoft also has a lot of free resources for beginners here:
    http://msdn.microsoft.com/en-us/beginner/default.aspx

  13. ME said on January 11, 2009 at 10:55 am
    Reply

    whoops

    vb
    for i as Integer = 0 to 99
    msgbox “hello world”
    next i

  14. ME said on January 11, 2009 at 10:40 am
    Reply

    FOR LOOPS

    php
    for($i=0; $i=99; $i++){
    echo ‘why post about this, let them learn the hard way :)’;
    }

    vb
    for i as string = 0 to 99
    msgbox “hello world”
    next i

    c#

    for (int i = 1; i <= 10; i++)
    {
    MessageBox.Show(“Hello World”);
    }

Leave a Reply

Check the box to consent to your data being stored in line with the guidelines set out in our privacy policy

We love comments and welcome thoughtful and civilized discussion. Rudeness and personal attacks will not be tolerated. Please stay on-topic.
Please note that your comment may not appear immediately after you post it.