PHP foreach value by reference

[img_assist|nid=9|title=|desc=|link=none|align=right|width=100|height=66] PHP5 added a very subtle yet very handy feature in the foreach Control Structure. It is the ability to access the value in the iteration as a reference to the original array.

The best way to demonstrate this is to establish an objective.

Objective: Write a function to capitalize all elements of an array.

There's at least 3 general ways we could go about this but obviously I'd like to show you how this can be accomplished using foreach with the value of each iteration as a reference.

<?phpfunction capitalizeArray($array) {  // make sure input is an array, and return an array if it isn't just to be nice.  if (!is_array($array)) {    return array();  }  // create a foreach structure with '&' before the value to access it as a reference  foreach ($array as &$value) {    // set $value t uppercase    $value = strtoupper($value);  }  // return the array  return $array();}?>

Notice we did not need to access the original array with a key to change the values inside of it. i.e. $array[0] = strtoupper($array[0]);

Remember that this will not work in PHP4 so don't use it if your code needs to be backwards compatible.