PHP

Chunk Array With Preserved Keys

admin by @admin ADMIN
Jun 16, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Slice an array into chunks of a given size while preserving the original keys in each chunk. Useful for paginating ordered datasets without losing the row IDs.
PHP
Raw
<?php
function chunkPreserveKeys(array $arr, int $size): array {
    $chunks = [];
    $i = 0;
    foreach ($arr as $k => $v) {
        $chunks[intdiv($i++, $size)][$k] = $v;
    }
    return $chunks;
}

$data = [10=>'a', 20=>'b', 30=>'c', 40=>'d', 50=>'e'];
print_r(chunkPreserveKeys($data, 2));
// [0 => [10=>a, 20=>b], 1 => [30=>c, 40=>d], 2 => [50=>e]]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.