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.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <img> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h3> <h4> <h5> <h6> <h7>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.