Accessing Values by Referrence in a Foreach Loop

Here’s a fun little trick. When looping over an array, you can access the values by reference. Instead of:

foreach ($things as $i => $thing)
{
  $things[$i] = strtolower($thing);
}

You can reference the values of the array:

foreach ($things as &$thing)
{
  $thing = strtolower($thing);
}

It’s a small difference, but it comes in handy once in a while, especially when you’re doing more significant processing with each item.

This entry was posted in Uncategorized and tagged . Bookmark the permalink.

3 Responses to Accessing Values by Referrence in a Foreach Loop

  1. This is a test to see if this comment is fed through the feed syndication and ends up on weblacarte.com.

  2. OhkaBaka says:

    I love this… I’ve been having these little discoveries a lot myself recently… though I keep forgetting to blog them.

    Oh thats right… I keep forgetting to finish building my site so I CAN blog them…

  3. OhkaBaka says:

    HAH!

    I haven’t posted here since the rebuild… I’m happy to see it remembers who the pimp is.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">