array_merge not working as expected

Tschallacka picture Tschallacka · Jul 2, 2012 · Viewed 11.1k times · Source

I have an double level array. On the first level there are about 10 indexes. These contain each to a 275 element array which each contains a word.

Array
(
[0] => Array
    (
    [0] => Suspendisse
    [1] => Nam.
    [2] => Amet
    [3] => amet
    [4] => urna
    [5] => condimentum
    [6] => Vestibulum
    [7] => sem
    [8] => at
    [9] => Curabitur
    [10] => lorem
    .... to [275]
    )
[1] => Array
    (
    ... you get the idea
    )
... 10 elements total
)

Now, through circumstances, like an added image that takes up space, I sometimes need to recalculate the number of words that are remaining and redistribute the array that still remains.

For that I have written the below function to make the remaining array one big long array of words, that I can array_chunk then to the right proportions. &$array is the reference to the "mother array", $memory is an array of words that are surplus, $index is where we are iterating through a for loop, $limit is "array" length for the 2nd level, in this case 275

function redistribute(&$array,$memory,$index,$limit)
{
$ret[] = $array[0];
// skip past the current processed items
for($c=1;$c<$index;$c++)
    {
    $ret[] = $array[$c];
    }
// apply current item
$ret[] = $array[$index];

//join the rest into one big array off words;
$r2=$memory;
$length = count($array);
for($c=$index+1;$c<$length;++$c)
    {
    array_merge($r2,$array[$c]);
    print_r($r2);
    }
}

The question

array_merge(arr1,arr2) doesn't seem to work.

when executing

redistribute($splitupchunk,array('test','test2','test3','test4'),$i,275);

print_r($r2) just prints test numbers without the extra variables from $array[$c]. How do I fix this?

Answer

Tschallacka picture Tschallacka · Jul 2, 2012

I found the reason why it didn't work. I assumed that array_merge worked by reference instead of by return.

By making the line

array_merge($r2,$array[$c]);

$r2 = array_merge($r2,$array[$c]);

It now works as expected.