PHP

Divide a PHP Array into Chunks (Pagination Helper)

Efficiently split a large PHP array into smaller, more manageable sub-arrays using `array_chunk`, ideal for pagination or batch processing tasks.

<?php
$items = range(1, 15); // Create an array from 1 to 15

// Divide into chunks of 4 items each
$chunks = array_chunk($items, 4);

/*
$chunks will be:
[
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15]
]
*/

// Divide into chunks of 3 items, preserving keys
$associativeItems = [
    'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4,
    'e' => 5, 'f' => 6, 'g' => 7
];
$chunksPreservingKeys = array_chunk($associativeItems, 3, true);

/*
$chunksPreservingKeys will be:
[
    ['a' => 1, 'b' => 2, 'c' => 3],
    ['d' => 4, 'e' => 5, 'f' => 6],
    ['g' => 7]
]
*/
?>
How it works: The `array_chunk` function splits an array into new arrays, each containing `size` number of elements. The last chunk may contain fewer elements if the original array's size is not perfectly divisible. The optional third parameter (`preserve_keys`) determines if the original keys should be maintained or reset to numeric (0, 1, 2...). This is useful for pagination or processing data in batches.

Need help integrating this into your project?

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

Hire DigitalCodeLabs