1

I have two arrays in PHP with a number of equal indices like this:

ARRAY 1 :

array (size=3)
  0 => 
    array (size=8)
      0 => int 1
      1 => int 17
      2 => int 145
      3 => string 'one' (length=3)
      4 => string '#3546b140' (length=9)
      5 => string '5' (length=1)
      6 => string 'ONE' (length=3)
      7 => string 'ONE' (length=3)
  1 => 
    array (size=8)
      0 => int 2
      1 => int 30
      2 => int 224
      3 => string 'two' (length=3)
      4 => string '#3546b140' (length=9)
      5 => string '6' (length=1)
      6 => string 'TWO' (length=3)
      7 => string 'TWO' (length=3)
  2 => 
    array (size=8)
      0 => int 3
      1 => int 31
      2 => int 120
      3 => string 'thr' (length=3)
      4 => string '#3546b140' (length=9)
      5 => string '7' (length=1)
      6 => string 'THR' (length=3)
      7 => string 'THR' (length=3)

This is the second array

array (size=3)
  1 => int 1761693
  2 => int 8911775
  3 => int 3510858

This would be the desired result, look at the eighth position of each index, any ideas?

array (size=3)
  0 => 
    array (size=8)
      0 => int 1
      1 => int 17
      2 => int 145
      3 => string 'one' (length=3)
      4 => string '#3546b140' (length=9)
      5 => string '5' (length=1)
      6 => string 'ONE' (length=3)
      7 => string 'ONE' (length=3)
      8 => int 1761693
  1 => 
    array (size=8)
      0 => int 2
      1 => int 30
      2 => int 224
      3 => string 'two' (length=3)
      4 => string '#3546b140' (length=9)
      5 => string '6' (length=1)
      6 => string 'TWO' (length=3)
      7 => string 'TWO' (length=3)
      8 => int 8911775
  2 => 
    array (size=8)
      0 => int 3
      1 => int 31
      2 => int 120
      3 => string 'thr' (length=3)
      4 => string '#3546b140' (length=9)
      5 => string '7' (length=1)
      6 => string 'THR' (length=3)
      7 => string 'THR' (length=3)
      8 => int 3510858

I have tried to do this but it does not work!!!

array_merge($array1,$array2);

and this

array_push($array1, $array2);

Iterating with a foreach but I can't position correctly the arrays by indices, any idea?

1 Answer 1

4

Loop through the first array and add the value from the second:

foreach ($array1 as $index => $subArray) {
    // We use $index + 1 since the first starts with 0 and the second with 1
    // We're also using $array1 since $subArray is just a copy so adding to that
    // won't change the original array
    $array1[$index][] = $array2[$index + 1];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer 😍😍, Initially I have a misunderstanding then I realize why you increment +1. Good work man. 👏

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.