Thursday, March 31, 2011

PHP: array modifications that persist beyond the scope of a foreach 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?

<?PHP
    include('magpierss/rss_fetch.inc');
    /*
        one, two, skip a few...
        $urls is an associative array with 
        database indices as keys and 
        URLs as values
    */

    foreach ($urls as $url_hsh)
    {
        $feed_id = $url_hsh[0];
        $url     = $url_hsh[1];

        echo $feed_id . "<br/>" . $url . "<br/>"; // works as expected

        $rss = fetch_rss($url); // from 'magpierss/rss_fetch.inc' above

        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..... 
        }
    }
?>

thanks

From stackoverflow
  • 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

    Keyo : Thanks I don't know how many times I have come up against this problem. Can read from the $item but not write to it. That is because it makes a copy I guess.

0 comments:

Post a Comment