In PHP, how do I chunk arrays in a memory-efficient way?

In PHP, you can chunk arrays using the built-in `array_chunk` function. This function splits an array into multiple smaller chunks. However, to manage memory efficiently, especially with large arrays, you might want to process chunks one at a time. Below is an example of how to do this:

<?php function chunkArrayMemoryEfficiently($array, $chunkSize) { // Get the total number of elements in the array $totalElements = count($array); // Iterate through the array in chunks for ($i = 0; $i < $totalElements; $i += $chunkSize) { // Create a chunk of the array $chunk = array_slice($array, $i, $chunkSize); // Process the chunk (you can perform your logic here) // For demonstration, we will just print the chunk print_r($chunk); // Clear the chunk for memory efficiency unset($chunk); } } // Example array to chunk $largeArray = range(1, 1000); chunkArrayMemoryEfficiently($largeArray, 100); ?>

PHP array chunking memory efficiency array manipulation PHP functions