Home > front end >  PHP cant add new object keys in foreach loop
PHP cant add new object keys in foreach loop

Time:10-17

I want to create new object keys in foreach loop so I write:

$all_variants = $p->variants;
        foreach ($all_variants as $a) {
                $a->discount_price = $a->price;
                $a->original_price = $a->price;
                $a->button_text = 'BUY';
           
        }

but this code wont create new keys (discount_price, original_price, button_text) ... $all_variants->discount_price is undefinded .... Whats bad in my code?

CodePudding user response:

You can use next trick for this

$all_variants = $p->variants;
foreach ($all_variants as &$a) {
    $tmp = (array)$a;
    $tmp['discount_price'] = $tmp['price'];
    $tmp['original_price'] = $tmp['price'];
    $tmp['button_text'] = 'BUY';
    $a = (object)$tmp;
}

Here object converted to array modified and converted to object again

php code online test

CodePudding user response:

This works for me:

foreach ($p->variants as $a) {
                $a['discount_price'] = $a['price'];
                $a['original_price'] = $a['price'];
                $a->button_text = 'BUY';
            
            $all_variants[] = $a;
            }

CodePudding user response:

You can modify the original array, but not the copy of the element you get in the loop...

foreach($p->variants as $i => $a) {
    // $p->variants[ $i ] corresponds to $a
    $p->variants[ $i ]['discount_price'] = $a['price'];
}
  • Related