4

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'] = '';        
      }
10
  • 1
    When doing foreach, PHP creates copies so doing $value = something doesn't actually affect the original array Commented Aug 17, 2014 at 17:30
  • Try passing $value by reference Commented Aug 17, 2014 at 17:30
  • In addition, your array appears to be an indexed array of associative arrays. You could do for ($i=0; $i<count($data); $i++){ $data[$i]['something'] = 'something'; } Commented Aug 17, 2014 at 17:31
  • @Jonathon I agree with your first comment but i don't with second. The foreach loop works Commented Aug 17, 2014 at 17:33
  • @Jonathon That would add the overhead of calling the count() function on every iteration of the loop. Commented Aug 17, 2014 at 17:36

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Manual also contains this warning, which is good practice: Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset(). In this case, an unset($value); statement should be added right below the loop.
@yitwail: I see that as noise. If the scope of the $value isn't clear at first glance, you probably should do some refactoring anyways.
3

In the foreach loop, pass the $value by reference by adding an ampersand & before the variable name:

foreach($data as $key => &$value)

This will allow the loop to modify the original $data instead of modifying a copy of it.

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.