Loop through an Array

Question
How do you loop through the elements of an Array?

A simple for loop

This technique can be used only for arrays that are zero based, i.e. where you haven’t specified a value for the key. If you have specified keys for your array, then you'll need to use either Technique 2 or Technique 3.

$busy_period = array('May', 'June', 'July');
 
//display the individual elements of the array
for($i = 0; $i < sizeof($busy_period); $i++)
  {
  echo '<br />' . $busy_period[$i];
  }

Output

May
June
July

A simple foreach loop

This technique uses the special foreach loop which cycles through each element of the array. This is the most common technique for cycling through elements of an array because the foreach loop works with any kind of index values.

$busy_period = array(5 => 'May', 6 => 'June', 7 => 'July');
 
//display the individual elements of the array
foreach($busy_period as $key => $value)
  {
  echo '<br />Key Value: ' . $key . ' element value: ' . $value;
  }

Output

Key Value: 5 element value: May
Key Value: 6 element value: June
Key Value: 7 element value: July

A for loop with key, current and next array functions

This technique shows how to use a standard for loop on an array that is not zero indexed based. It uses the key, current and next functions to retrieve the key, current array element value and move the pointer to the next element in the array.

$busy_period = array(5 => 'May', 6 => 'June', 7 => 'July');
 
//display the individual elements of the array
for($i = 0; $i < sizeof($busy_period); $i++)
  {
  $month_number = key($busy_period);        //get the key value (e.g. 5)
  $month_name   = current($busy_period);    //get the element value (e.g. ‘May’)
 
  echo '<br />Key Value: ' . $month_number . ' element value: ' . $month_name;
  next($busy_period);			    //move to the next array element.
  }

Output

Key Value: 5 element value: May
Key Value: 6 element value: June
Key Value: 7 element value: July

Comments

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.