PHP: array_merge an array with itself

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:

$fruits = array( 'Apples', 'Oranges', 'Bananas', 'Strawberries' );
$fruits = array_merge( $fruits, $fruits);
echo implode( ', ', $fruits);

This yields: Apples, Oranges, Bananas, Strawberries, Apples, Oranges, Bananas, Strawberries

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:

$fruits = array( 'Apples', 'Oranges', 'Bananas', 'Strawberries' );
for($i=0; $i<11; $i++) {
    $fruits = array_merge( $fruits, $fruits);

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:

How many elements you'll end up with:

(2^[number of iterations]) * [starting array count]
(2^11) * 4 = 8192

How many times to loop to achieve a certain length:

ln( [desired final array count] / [starting array count] ) / ln(2)
ln( 10000/4 ) / ln(2) = ln(2500) / ln(2) = 11.3
Always iterate to the next highest integer, so 11.3 = 12 iterations

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.

No Comments »
date Jan 2nd 2013
author Mike
category Geek
tags, ,
  No Comments »