php resource centre

  • about
  • articles
  • tutorials
  • resources
  • certification
Home

Primary links

  • About
  • Articles
  • Tutorials
  • Resources
  • Certification

Foreach Loop

admin — Wed, 13/09/2006 - 8:25pm

foreach loop

Foreach is a construct used to loop through arrays. There are mainly 2 types of usages :



The basic foreach loop syntaxes are shown below:

foreach (array as $value) {    
  statement
}
   
foreach (array as $key => $value) {
    statement
}

The first type of foreach loop is used to loop over an array denoted byarray. During each iteration through the loop, the current value of the array is assigned to the variable - $value and the loop counter is incremented by a value of one. Looping continues until the foreach loop reaches the last element or upper bound of the given array. During each loop, the value of the variable - $value can be manipulated but the original value of the array remains the same. To change the actual value of the array, it is necessary to replace the "$" symbol with the "&" symbol. Any changes made to &value, can be assigned to the array element at the current index.

The following example demonstrates how the foreach loop is used to interate over the values of an array:

<?php
$my_array = array('red','green','blue');
echo "The different colors include: ";
foreach($my_array as $value)
 {
 $colors .= $value . " "; 
}
 echo $colors;
?>

During each loop, the color name associated with the current array element is assigned to a variable - $colors. A single space " " is also added between each of the color names for display purposes. When the loop reaches the end of the array, the output below is generated:

The different colors include: red green blue

The second form of the loop provides the same functionality as the first, but also assigns the current array element's index or key to be assigned to the variable - $key on each loop. In the previous example, the array $my_array contains three elements: $my_array[0] = "red", $my_array[1] = "green", and $my_array[2] = "blue". While the variable - $value contains the array element values: red, green, and blue, the variable $key contains the array element indices: 0, 1, and 2.

  • Tutorials
  • Login to post comments

User login

  • Request new password

Follow Us

Who's online

There are currently 0 users and 1 guest online.

Who's new

  • Nisha
  • linnaeus
  • Yameen
  • TalleyReedy
  • admin

Follow vipin7873 on Twitter

  • about
  • articles
  • tutorials
  • resources
  • certification

copyright © 2010 Vipin Chandran