Pass Foreach Variables by Reference (PHP)

A recent trick I discovered while working on a Drupal module is the ability to pass the array element into a foreach loop by reference. Like so:

$array = array(1, 2, 3, 4, 5);

foreach ($array as &$element) {
  if ($element == 3)
    $element = 6;
}

print_r($array);

Your output would be:

Array
(
    [0] => 1
    [1] => 2
    [2] => 6
    [3] => 4
    [4] => 5
)

Not only does this save on memory, it also allows you to change the actual items in the array. Quite useful.

Another example:

$array = array(
  'cow' => 'moo',
  'pig' => 'oink',
  'cat' => 'meow',
);

foreach ($array as $key => &$element) {
  if ($key == 'cat')
    $element = 'bark!';
}

print_r($array);

Output:

Array
(
    [cow] => moo
    [pig] => oink
    [cat] => bark!
)

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>