4

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

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

PHP offers several ways to mutate iterable data.

  • Use array_map() with the union operator to append a new elements to each row. Demo

    $feedId = 42;
    $rss->items = array_map(
        fn($item) => $item + ['feed_id' => $feedId],
        $rss->items
    );
    var_export($rss);
    
  • Telling a foreach() loop to modify the original array instead of a copy of the input array is done by prepending an ampersand to the row variable declaration. Demo

    $feedId = 42;
    foreach ($rss->items as &$item) {
        $item['feed_id'] = $feedId;
    }
    var_export($rss);
    
  • Iterate a copy of the input array, but then access the keys and use them to affect the original array. (Demo)

    $feedId = 42;
    foreach ($rss->items as $key => $item) {
        $rss->items[$key]['feed_id'] = $feedId;
    }
    var_export($rss);
    

As a divergence of the proposed scenario, but topically related, if the input is an array of objects, a foreach() will iterate the original array (not a copy) without needing a prepended ampersand. Demo

$items = [
    (object) ['foo' => 'bar1'],
    (object) ['foo' => 'bar2'],
    (object) ['foo' => 'bar3'],
];

$feedId = 42;
foreach ($items as $obj) {
    $obj->feed_id = $feedId;
}
var_export($items);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.