1

i am trying to loop through two multi-dimensional array with a foreach loop

[array1] => Array ( 
[0] => Array ( 1,2,3 ) 
[1] => Array ( 4,5,6 ) 
[2] => Array ( 7,8,9 )
  )
[array2] => Array ( 
[0] => Array ( 1,2,3 ) 
[1] => Array ( 4,5,6 ) 
[2] => Array ( 7,8,9 ) ) 
  )

both has same keys,

i want to access 1st array of both arrays at same time, i want to do something like this

foreach($array1 as $key1=>$value1 && $array2 as $key2=>$value2)
    echo $value1[1]."  ".$value2[2]

its not correct, but that's what i want to do !!

2
  • is both array index is same??? Commented Jan 14, 2014 at 7:58
  • yes, key upto 1st level are same in both array Commented Jan 14, 2014 at 8:03

3 Answers 3

3

If the keys are identical between the two arrays in both dimensions :

foreach (array_keys($array1) as $key1) {
    foreach (array_keys($array1[$key1]) as $key2) {
        echo $array1[$key1][$key2].' '.$array2[$key1][$key2];
    }
}

Worst case scenario, some keys in one dimension or the other are missing in one or both arrays and you have to merge them prior to reading (and ensure the existence of the key's value in each loop & array).


UPDATE: used the same solution twice for two-dimensional array structure.

Sign up to request clarification or add additional context in comments.

2 Comments

but i want to extract array values
See my update, you just have to apply the same logic to the 2nd dimension as well as the first.
1

im not sure if you can do this, i would use a for loop instead:

for(i=0; i < count($array1); i++)
{
   for(j=0; j < count($array1[i]); j++)
   {
       echo $array1[i][j];
       echo $array2[i][j];
   }
}

1 Comment

thanks, i thought that we cant loop through associative array in this way, so i never tried it. but now my confusion is solved.
1

You can use this code, because you have same keys

foreach($array1 as $key=>$value) {
    for($i=0; $i < count($value); $i++) {
        echo $value[$i]."  ".$array2[$key][$i];
    }
}

Thanks Maks3w for your comment.

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.