PHP array_chunk function

Syntax of array_chunk

array array_chunk(array array, int size[, int preserve_keys])

Splits array into a series of arrays, each containing size elements, and returns them in an array. If preserve_keys is true (default is false), the original keys are preserved in the resulting arrays; otherwise, the values are ordered with numeric indices starting at 0

Example of array_chunk

<?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
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

Leave a Comment