By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

How to Loop Through an Array in PHP

How to loop trough an array in PHP

Edited: 2014-12-28 04:06

This PHP tutorial will teach you how you can easily loop through an array. In the first example script, we will be looping through our array with a normal while loop. Using this method may be faster than using a foreach loop, but the foreach loop is generally easier to use.

In this first example, we first count the elements in our PHP array, then we run the while loop until our counter reached the number of elements in the array – example below:

$aMyArray['0'] = 'One';
$aMyArray['1'] = 'Two';

 $n = count($aMyArray); // Count the number of Elements in array

 $counter = 0; // Initialize the counter variable
 while ($counter < $n) {
   echo $aWords["$counter"] . '<br>';
   ++$counter; // Increment the counter by 1

PHP loop trough array with foreach

The PHP foreach loop deserves its own section – this loop is intended to be used with arrays and objects – but it's also slower than loops where you first count the number of elements present in the array, presumably because it checks if the last element has been reached over and over again.

Do not be frightened by this however, as normally this won't be a problem – so if you think the foreach PHP loop is easier to work with, you shouldn't hesitate to use it – example below:

$aMyArray['0'] = 'One';
$aMyArray['1'] = 'Two';

foreach ($aMyArray as &$value) {
    echo $aMyArray . '<br>';

More PHP Array Tutorials

  1. Determine the Length of an Array
  2. Find Elements or Keys in Array
  3. Create an Array From a List of Keywords with Explode