Split an Array into Chunks Without Using PHP Functions
Here’s how you can manually split an array into smaller chunks without using PHP’s built-in array_chunk function.
Code Example:
function splitArrayIntoChunks($array, $chunkSize) {
$chunks = [];
$currentChunk = [];
$counter = 0;
foreach ($array as $value) {
$currentChunk[] = $value; // Add value to the current chunk
$counter++;
// When the chunk reaches the desired size, add it to the result
if ($counter === $chunkSize) {
$chunks[] = $currentChunk;
$currentChunk = []; // Reset the current chunk
$counter = 0; // Reset the counter
}
}
// Add any remaining elements as the last chunk
if (!empty($currentChunk)) {
$chunks[] = $currentChunk;
}
return $chunks;
}
// Example Usage
$array = [1, 2, 3, 4, 5, 6, 7, 8];
$chunkSize = 3;
$result = splitArrayIntoChunks($array, $chunkSize);
print_r($result);
Output:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
[1] => 8
)
)
Explanation
- Initialize Variables:
- $chunks: The final array to hold the chunks.
- $currentChunk: Temporary array to hold the current chunk.
- $counter: Tracks how many elements have been added to the current chunk.
- Iterate Through the Array:
- Add each element to the $currentChunk.
- Increment the $counter.
- Check Chunk Size:
- Once the $counter equals the desired chunk size ($chunkSize), move the $currentChunk to the $chunks array and reset $currentChunk and $counter.
- Handle Remaining Elements:
- If there are any elements left in $currentChunk after the loop, add them as the final chunk.
This approach gives you a manual implementation of chunking without using PHP functions.
Keep Learning 🙂