blog-banner

Iterate 2 Arrays in a Single Foreach Loop

  • Drupal 7
  • Drupal Module
  • PHP

Foreach Loop in PHP

 

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 baffling 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 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 that 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 someone as it did in my case.

Get awesome tech content in your inbox