Jul 8 2010

I have a case at work where I needed to go through a big list of arrays, and add them to a new master array. It turns out this is incredibly slow when adding many large arrays to a larger array. The alternative to this if you don’t care about keys or duplication of values is to just add it into the array. So normally where one might do something like:

$big_array = array();
foreach($array_of_objs as $obj)
{
  $row = $obj->getSomeData(); // returns an array of data
  $big_array = array_merge($big_array, $row);
}
processData($big_array);

I believe that array_merge creates a new array every time which is what was slowing it down. The solution was simple enough, it just took me a while to think of! :)

$big_array = array();
foreach($array_of_objs as $obj)
{
  $row = $obj->getSomeData(); // returns an array of data
  foreach($row as $r)
  {
    $big_array[] = $r;
  }
}
processData($big_array);

This was vastly faster, again possibly because it doesn’t create a new array every time. There are limitations to this method, and it doesn’t do exactly the same thing as array_merge, but it does do what I needed it do, so if anyone has a similar situation, I hope this helps!

One Response to “Alternative to array_merge merging many arrays”

  1. Stefan says:

    This helped, thanks.

Leave a Reply