coder1.com

  • home
  • drupal articles
  • contact
Home

PHP foreach value by reference

Mike Milano — July 1, 2008 - 10:49pm

[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.

  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.

  • Control Structures
  • PHP

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.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. The supported tag styles are: <foo>, [foo].

More information about formatting options

Poll

Have you checked out Drupal 7 yet? (still alpha):

User login

  • Request new password

Navigation

  • Recent posts
  • home
  • drupal articles
  • contact