Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Looping through data with PHP

Wednesday, December 12th, 2012 by Servage

Looping code in PHP is one of the most powerful language constructs available to iterate over data and manipulate it – item by item – for for a given amount of times. You can use loops to go through each part of a selection and do something with it. Or repeat a given dynamic action a predfined number of times to reach your desired goal.

There are three different types of loops in PHP: For, Foreach and While loops are available. They are different in the way they handle the data to loop though and how to decide when to stop looping. They are all similar in they construction, as they resemble the following example:

LoopType (Condition) {
  Code to be executed;

While loop example

The following code runs 10 times.

while( $i <= 10 ) {
  echo "The number is " . $i . "<br />";

For loop example

The following code also runs 10 times. The for loop has more parameters to set. For example could the increment per iteration be any number, not just 1.

for ($i=1; $i<=10; $i++) {
  echo "The number is " . $i . "<br />";

Foreach loop example

The foreach loop uses an array to loop thorugh. The following runs 3 times, because there are three elements in the array to loop through.

$array = array('a','b','c');
foreach ($array as $key => $value) {
  echo "The key is " . $key . " and the value is " . $value . "<br />";

Given the examples above, I hope you understand what potential lies within using loops to help you produce powerful code for your website.

Looping through data with PHP, 3.8 out of 5 based on 5 ratings
Categories: Guides & Tutorials, Tips & Tricks


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.