PHP

How to Chunk a PHP Array into Smaller Arrays

Learn to split a large PHP array into multiple smaller arrays with a specified size, perfect for pagination, batch processing, or displaying data in groups.

<?php
$items = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape'];
$chunk_size = 3;

$chunks = array_chunk($items, $chunk_size);

print_r($chunks);

// Output:
// Array
// (
//     [0] => Array
//         (
//             [0] => apple
//             [1] => banana
//             [2] => cherry
//         )
//
//     [1] => Array
//         (
//             [0] => date
//             [1] => elderberry
//             [2] => fig
//         )
//
//     [2] => Array
//         (
//             [0] => grape
//         )
//
// )

$associative_items = [
    'id_1' => 'Product A',
    'id_2' => 'Product B',
    'id_3' => 'Product C',
    'id_4' => 'Product D',
    'id_5' => 'Product E'
];

// Preserve keys (optional third argument)
$associative_chunks = array_chunk($associative_items, 2, true);
print_r($associative_chunks);

// Output:
// Array
// (
//     [0] => Array
//         (
//             [id_1] => Product A
//             [id_2] => Product B
//         )
//
//     [1] => Array
//         (
//             [id_3] => Product C
//             [id_4] => Product D
//         )
//
//     [2] => Array
//         (
//             [id_5] => Product E
//         )
//
// )
?>
How it works: The `array_chunk()` function splits an array into new chunks (sub-arrays) of a specified size. This is extremely useful for pagination, batch processing, or displaying data in manageable groups. The first argument is the input array, and the second is the desired chunk size. An optional third boolean argument, `preserve_keys`, determines if the original keys should be preserved in the new chunks; by default, numeric keys are re-indexed.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs