Programming:PHP/foreach loop

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Return to PHP.

Contents

[edit] The Code

foreach ($array as $someVar) {
  echo ($someVar . "<br />");
}

or:

foreach ($array as $key => $someVar) {
  echo ($someVar . "<br />");
}

[edit] Analysis

The foreach loop is a special form of the standard for loop. The example above will print all the values of $array. The foreach structure is a convenient way to loop through an array.

[edit] simple foreach statement

Foreach loops are useful when dealing with an array indexed with arbitrary keys (e.g. non-numeric ones):

$array = array(
  "1st" => "My House",
  "2nd" => "My Car",
  "3rd" => "My Lab"
);

To use the classical for structure, you'd have to write:

// get all the array keys
$arrayKeys = array_keys($array);
// loop through the keys
for ($i=0; $i<count($array); $i++) {
  // get each array value using its key
  echo $array[($arrayKeys[$i])] . "<br />";
}

Basically, an array value can be accessed only from its key: to make sure you get all the values, you first have to make a list of all the existings keys then grab all the corresponding values. The access to first aray value, the previous example does the following steps:

$firstKey = $arrayKeys[0]; // which is '1st'
$firstValue = $array[$firstKey]; // which is 'My House' ($array('1st'))

The foreach structure does all the groundwork for you:

foreach ($array as $someVar) {
   echo $someVar . "<br />";
}

Note how the latter example is easier to read (and write). Both will output:

My House
My Car
My Lab

[edit] foreach with key values

If you need to use the array keys in your loop, just add the variable as in the following statement:

foreach ($array as $myKey => $value) {
  // use $myKey
}
This form mimics the way we used custom keys for $array elements. It will not only assign the elements of $array to $someVar, but also assign the keys of those elements to $i.


PHP Code:

<?php
$array = array("1st" => "My House", "2nd" => "My Car", "3rd" => "My Lab");
foreach ($array as $i => $someVar) {
  echo $i . ": " . $someVar . "<br />\n";
}
?>

PHP Output:

 1st: My House<br />
 2nd: My Car<br />
 3rd: My Lab<br />

HTML Render:

 1st: My House
 2nd: My Car
 3rd: My Lab


Note that if you change the assigned variable inside the foreach loop, the change will not be reflected to the array. Therefore if you need to change elements of the array you need to change them by using the array key. Example:

$array = array(
  "1st" => "My House",
  "2nd" => "My Car",
  "3rd" => "My Lab"
);
 
foreach ($array as $i => $someVar) {
 
  // OK
  if($someVar == 'My Lab')
    $array[$i] = 'My Laboratory';
 
  // doesn't update the array
  $someVar = 'Foo';
}
Personal tools