PHP array_chunk Function: Splitting an Array into Chunks

This article explains PHP’s array_chunk function, describing its parameters, return value, and optional key preservation, and provides clear example code that demonstrates how an input array can be divided into equally sized sub‑arrays.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP array_chunk Function: Splitting an Array into Chunks

The array_chunk function splits a given array into multiple sub‑arrays, each containing a number of elements defined by the $size argument; the final chunk may contain fewer elements.

Parameters $input – the array to be processed. $size – the number of elements each chunk should contain. $preserve_keys – optional boolean (default false). When set to true, the original keys are retained; otherwise, each chunk receives new numeric indexes starting from zero.

Return value

A multidimensional array where each element is a chunk of the original array, indexed from zero.

Example

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

Output

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )
    [1] => Array
        (
            [0] => c
            [1] => d
        )
    [2] => Array
        (
            [0] => e
        )
)

Array
(
    [0] => Array
        (
            [a] => a
            [b] => b
        )
    [1] => Array
        (
            [c] => c
            [d] => d
        )
    [2] => Array
        (
            [e] => e
        )
)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPArrayfunctionexamplesplitarray_chunk
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.