How to preallocate memory for an array in PHP? I want to pre-allocate space for 351 thousand lengths. The function works when I do not use an array, but if I try to store long values in an array, then this will not work. If I try a simple test loop to populate 351k values with range(), it works. I suspect the array is causing memory fragmentation and then running out of memory.
In Java, I can use ArrayList al = new ArrayList(351000);.
I saw array_filland array_padbut they initialize the array for specific values.
Decision:
I used a combination of answers. Kevin's answer worked alone, but I was hoping to prevent problems in the future as the size grows.
ini_set('memory_limit','512M');
$foundAdIds = new \SplFixedArray(100000);
$foundAdIdsIndex = 0;
$result = $gaw->getAds(function ($googleAd) use ($adTemplates, &$foundAdIds, &$foundAdIdsIndex) {
if ($foundAdIdsIndex >= $foundAdIds->count()) $foundAdIds->setSize( $foundAdIds->count() * 1.10 );
$foundAdIds[$foundAdIdsIndex++] = $googleAd->ad->id;