Loop through an array in PHP

Before seeing how we can traverse an array in PHP, the first thing we have to do is define the array itself. To do this we use the reserved statement array as follows.

$list = array("amaya","julio","javier","nacho","sonsoles");

As we can see in the code we have written we have an array with a list of names.

To loop through the array at PHP we will simply need a for structure, which iterates through the elements of the array. The for structure in PHP has the following form:

for (initial_assignment, condition, increment) { ... }

The idea is to iterate one by one until we have gone through all the elements. Thus, if we use a counter variable, the condition will be to not have reached the index of the last element.

To know how many elements the array has, we use the function
count()
. Thus the for loop will look like this:

for ($x=0;$x<count($list); $x++) { ... }

Now we only have to access the content of the array elements in each iteration. To access the content the following structure is used:

$list[item_index];

In it we can see that we use the square bracket operator to access the elements of the array. The square bracket operator will contain the index of the array we want to access.

Thus, our complete for loop will look like this:

for ($x=0;$x<count($list); $x++)
  echo $list[$x]."<br>";

The echo statement allows us to dump the contents of the list onto the screen. To this content we give a
br
which is a line break in HTML.

We have already traversed our array with PHP.


Update January 10, 2011

An optimization, as our colleague @ghizu comments, is to execute the function
count()
before entering the loop. This way it will only be invoked once.

$size = count($list);

for ($x=0;$x<$size; $x++)
  echo $list[$x]."<br>";

Leave a Comment