Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I'm not able to add new key value pair in an associative array?

I've a large associative array titled $data. For your understanding I'm printing below one element from it.

Array
(
    [0] => Array
        (

            [id] => 92
            [zip_code] => 07080
            [phone_no] => 7327630062
            [amount] => 
            [currency] => $
            [product_details] => Array
                (
                )

        )
    [1] => Array
        (

            [id] => 93
            [zip_code] => 07081
            [phone_no] => 7327630063
            [amount] => 20
            [currency] => $
            [product_details] => Array
                (
                )

        )
)

Now I want to create a new key-value pair in every element of the above associative array titled $data. For it I wrote following logic but it's not creating a new key-value pair. Can someone please help me in this regard?

foreach($data as $key => $value) {
        if(!empty($value['amount'])) { 
          $value['final_amount'] = $value['amount'] - 2;
        } else 
          $value['final_amount'] = '';        
      }
like image 859
PHPFan Avatar asked Feb 12 '23 05:02

PHPFan


1 Answers

From the manual of foreach:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

foreach($data as $key => &$value)
like image 113
Karoly Horvath Avatar answered Feb 15 '23 09:02

Karoly Horvath