I recently wanted to merge an array with itself, duplicating all of its own elements and appending them to the original array, over and over until it was thousands of times its original size. It took me a little while to find the best way to do this, so I thought I’d share what I found.

Luckily, you can use PHP’s array_merge() function to double the original array’s size. For example:

Awesome, we’ve made our 4 element array into an 8 element array. But what about making it much bigger? I was running speed tests, and wanted an array that had 10,000 elements or more,* so I needed to keep running these array merges. Doing array_merge( $fruits, $fruits, $fruits, ...) wouldn’t work since each additional argument only adds another 4 elements to the array.

The simplest thing to do is recursively duplicate the array, and compound the results. By doing this, the first iteration yields an 8 element array, the second has 16 elements, the third has 32, etc. Example of how to do this:

By running the for loop 11 times, you end up with an array with 8,192 elements, and increasing it to 12 your result has 16384 elements. If you need more elements, use the following equations to figure out how many times you need to loop through your array:

By using 12 iterations, you're sure to get at least 10,000. If you need a more exact number, you can always use array_splice() to truncate the result.

* For the speed test I was trying to manipulate database objects, and I only had 4 of them in the database. I wanted to see what would happen if I had tens-of-thousands of them in the database, hence the duplication.