PHP foreach value by reference

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.

  1. <?php
  2.  
  3. function capitalizeArray($array) {
  4. // make sure input is an array, and return an array if it isn't just to be nice.
  5. if (!is_array($array)) {
  6. return array();
  7. }
  8.  
  9. // create a foreach structure with '&' before the value to access it as a reference
  10. foreach ($array as &$value) {
  11.  
  12. // set $value t uppercase
  13. $value = strtoupper($value);
  14.  
  15. }
  16.  
  17. // return the array
  18. return $array();
  19. }
  20. ?>

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.

fixed, thanks.

fixed, thanks.

You're missing a $ in

You're missing a $ in &value, FYI