1

I would like to add values from a $secondArray to $firstArray:

$firstArray = [
    0 => [
        'prodID' => 101,
        'enabled' => 1,
    ],
    1 => [
        'prodID' => 105,
        'enabled' => 0,
    ],
   ];

The $secondArray will always have the same amount of array items and will be in the same order as the $firstArray:

$secondArray = [34, 99];

This is what I have tried but I keep getting the wrong stockQT values after the exercise:

foreach ($secondArray as $value) {
    foreach ($firstArray as &$firstArray) {
        $firstArray['stockQT'] = $value;
    }
}

Incorrect Result for a var_dump($firstArray):

array (size=2)
  0 => 
    array (size=3)
      'prodID' => int 101
      'subscribed' => int 1
      'stockQT' => int 99
  1 => 
    array (size=3)
      'prodID' => int 105
      'subscribed' => int 0
      'stockQT' => int 99

I have looked at similar posts but cant seem to get the correct vales after using different suggestions like while() loops. Below is what I need the $firstArray to look like:

array (size=2)
  0 => 
    array (size=3)
      'prodID' => int 101
      'subscribed' => int 1
      'stockQT' => int 34
  1 => 
    array (size=3)
      'prodID' => int 105
      'subscribed' => int 0
      'stockQT' => int 99
4
  • You want to loop through both arrays at once and then just add/merge the second array's values to the first one. Commented Aug 16, 2016 at 15:35
  • Try foreach($firstArray as $k=>$v){$firstArray[$k]['stockQT'] = $secondArray[$k];} Commented Aug 16, 2016 at 15:43
  • @Rizier123: No need to loop through both The $secondArray will always have the same amount of array items and will be in the same order as the $firstArray Commented Aug 16, 2016 at 15:46
  • Thanks for the quick response, problem resolved! Commented Aug 17, 2016 at 12:38

1 Answer 1

1

You just need one foreach() using the key since $secondArray will always have the same amount of array items and will be in the same order as the $firstArray. Notice the & to modify the actual value in the array:

foreach($firstArray as $key => &$value) {
    $value['stockQT'] = $secondArray[$key];
}

Or alternately loop $secondArray and use the key to modify $firstArray:

foreach($secondArray as $key => $value) {
    $firstArray[$key]['stockQT'] = $value;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just a side-note. The concept of looping was difficult enough for OP so I would advise against referencing &$value unless you add unset($value); after the loop completes.
Thanks, I implemented the first option and added a unset at the end. Much appreciated!

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.