Search code examples
phparraysloopsforeachreference

Modify original input array within a loop


How can I add a new key/value pair to an existing array inside of nested foreach loops and have that pair persist outside the scope of the loops?

foreach ($rss->items as $item)
{
    $item['feed_id'] = $feed_id;
    echo $item['feed_id'] . "<br/>"; // works as expected
}
    
foreach ($rss->items as $item)
{
    echo $item['feed_id'] . "<br/>"; // nuthin..... 
}

Solution

  • If I understand correctly, what you want is this (for the first loop):

    foreach ($rss->items as &$item) {
    

    The & will make $item be a reference, and any changes you make to it will be reflected in $rss->items