Skip to main content
array in single foreach loop

Iterate 2 arrays in a single foreach loop

The topic looks so simple isn't it? It looked simple to me when I ran into such a kind of need. The first and foremost PHP function that I thought to get this done was array_combine. It did produce the desired result, the below piece of code shows my implementation,

  1. foreach (array_combine($codes, $names) as $code => $name) {
  2.   print $code . 'is your Id code and '  . $name . 'is your name';
  3. }

I sent back the requirement packing and moved to my next assignment, but after a couple of days I was quite pestered about the performance factor of my implementation. What would happen if the size of the array is going to cross N? I had no answer to my own question, To stir up my baffle I came across this question in stackexchange. What looked like a perfect solution in minutes looked like a well executed coding mishap!

array_combine having O(n) can never be trusted in all the cases, once the array size goes beyond what the server can actually bear the results would be disastrous. Hence I looked into another alternate solution which would work great in any condition. The following piece of code shows the correct version of my implementation,

  1. foreach( $codes as $index => $code ) {
  2.   print $code . 'is your Id code and ' . $names[$index] . 'is your name';
  3. }

The above code just iterates through one of my  arrays, based on this array's key the second array's value is retrieved. Hope this helps some one as it did in my case.