How can the issue of an empty sub-array being produced be addressed in the PHP code?

Issue: The empty sub-array is produced because the $subArray variable is being initialized outside the loop, causing it to retain its value from the previous iteration. To address this issue, we need to reset $subArray to an empty array at the beginning of each iteration of the loop. PHP Code:

$mainArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$chunkSize = 3;
$result = [];

for ($i = 0; $i < count($mainArray); $i += $chunkSize) {
    $subArray = []; // Reset subArray to an empty array at the beginning of each iteration
    for ($j = $i; $j < $i + $chunkSize && $j < count($mainArray); $j++) {
        $subArray[] = $mainArray[$j];
    }
    $result[] = $subArray;
}

print_r($result);