note 98386 deleted from function.array-merge by cmb
| From: | cmb@php.net | Date: | Sun, 29 Sep 2019 07:36:33 +0000 |
| Subject: | note 98386 deleted from function.array-merge by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212405@lists.php.net to get a copy of this message | ||
Note Submitter: jpakin at gmail dot com
----
I had a hard time using array_merge with large datasets. By the time my web framework was in memory
there wasn't enough space to have multiple copies of my dataset. To fix this I had to remove
any functions which operated on the data set and made a copy in memory (pass by value).
I realize the available memory to an application instance is modifiable, but I didn't think I
should have to set it below the default 16mb for a web app!
Unfortunately, a number of php functions pass by value internally, so I had to write my own merge
function. This passes by reference, utilizes a fast while loop (thus doesn't need to call
count() to get an upper boundary, also a php pass by value culprit), and unsets the copy array
(freeing memory as it goes).
<?php
function mergeArrays(&$sourceArray, &$copyArray){
//merge copy array into source array
$i = 0;
while (isset($copyArray[$i])){
$sourceArray[] = $copyArray[$i];
unset($copyArray[$i]);
$i++;
}
}
?>
This fixed the problem. I would love to know if there is an even faster, more efficient way. Simply
adding the two arrays won't work since there is an overlap of index.