The PHP for() loop

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

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:

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

  1. 4 Responses to “The PHP for() loop”

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

    By Grateful on Oct 12, 2007

  3. 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 Mar 12, 2008

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

    By Con on Apr 15, 2008

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

    By Sarah on Apr 16, 2008

Post a Comment

Please use your real name, nickname or an online name. Names I consider spam will be changed.