0

I found a strange behavior in PHP foreach

foreach ($webshopOrders as $webshopOrder) {
    foreach ($webshopOrder['products'] as $product) {
        $product['item_no'] = preg_replace('/...my pattern.../', $myNewValue, $product['item_no']);
        // here the item_no contains the new, right value
    }
}

// here the item_no contains the original value

Why isn't changed the value permanently in the foreach and how can I set the value to use outside the foreach loop too?

netdjw
  • 5,419
  • 21
  • 88
  • 162
  • You're only editing the value in the foreach instead of overriding it outside the foreach. To do so you're better of using 2 for loops so you can do `$webshopOrders[$i]['products'][j]['item_no'] = preg_replace(...)` – SuperDJ Apr 17 '20 at 10:21
  • I found solution the other post: use `&` sign in this: `$webshopOrders as $webshopOrder`. Here is the working code: `$webshopOrders as &$webshopOrder` – netdjw Apr 17 '20 at 10:36

0 Answers0