Wednesday, February 22, 2012

Modifying an item in an array while iterating over it in PHP

So you want to iterate over an array in PHP and change each item as you do.
In PHP5 there are two ways of doing this.

1) Pass by reference
Note the ampersand in the declaration of the foreach loop before the variable $i, passing each item by reference and allowing it to be changed directly.
$arr = array('a', 'b', 'c');
foreach($arr as &$i) {
    $i = 'changed';
}
2) Using the key of each item
This is the classic way of achieving the same, using the key of the item
$arr = array('a', 'b', 'c');
foreach($arr as $k=>$v) {
    $arr[$k] = 'changed';
}

No comments:

Post a Comment