The PHP for() loop

And another loop for you to try is the for() loop. This repeats for a specified number of times.

[source:php]$num = 10
for ($i=0; $i < $num; $i++) {
print $num;
print "
";
}
[/source]

This will print out the numbers 0 to 9, each on a new line. With this loop we can also use it to combine variable variables to iterate through a series of repetitive form fields eg. name1, name2 and name3.

For example:

[source:php]for ($i=1; $i < $num_fields; $i++) {
$temp = "name".$i;
print $$temp."
";
}
[/source]

As you can see you create a dynamic variable name using the value of $i (1, 2, 3 etc) and then save this string in the variable $temp. Therefore on the first iteration $temp contains "name1". To get this to display the content of $name1 you need to use two dollar signs to get the variable variable ie. $$temp. This is very handy when you do not know how many text boxes may be coming from a form, such as in an ecommerce shopping basket. This way if each box has a generic name plus a number on the end which increments each time, it is easy to pass through the count of fields from the form page (which is then stored as $num_fields) and then it can display the code. Plus imagine having 20 text boxes. Compare 20 lines of code to just 4!

Additional Note: To access the form fields you would use slightly different code as below

[source:php]for ($i=1; $i < $num_fields; $i++) {
print $_POST['name'.$i]."
";
}
[/source]

4 Responses to “The PHP for() loop”

  1. Thanks That was just what I was looking for!

    By Grateful on Fri, 12 October, 2007

  2. This line:
    $_POST['name'.$i]
    saved my bacon. I couldn't figure out how to cycle through my variable names!
    Thank you a million times!

    By basic php learner on Wed, 12 March, 2008

  3. How can i save the variables into a text file?

    By Con on Tue, 15 April, 2008

  4. Hi Con, you need to use the fwrite() function.

    By Sarah on Wed, 16 April, 2008

Leave a Comment

Please use your real name or nickname. Spam names will be changed.