Array Functions
Advertisements

PHP array_chunk() Function

Topic: PHP Array ReferencePrev|Next

Description

The array_chunk() function splits an array into chunks.

The following table summarizes the technical details of this function.

Return Value: Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing size elements.
Version: PHP 4.2+

Syntax

The basic syntax of the array_chunk() function is given with:

array_chunk(array, size, preserve_keys)

The following example shows the array_chunk() function in action.

<?php
// Sample array
$colors = array("red", "green", "blue", "orange", "yellow", "black");

// Split colors array into chunks
print_r(array_chunk($colors, 2));
?>

Parameters

The array_chunk() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.
size Required. A positive integer (greater than 0) which specifies the size of each chunk.
preserve_keys Optional. Specifies whether to preserve the origial keys or not. When set to TRUE the keys will be preserved. Default is FALSE which will reindex the chunk numerically.

Note: If you do not specify the preserve_keys parameter inside the array_chunk() function the chunks will be reindexed numerically, because the default value of this parameter is FALSE.


More Examples

Here're some more examples showing how array_chunk() function basically works:

The following example will split an array into chunks of two while preserving the original keys:

<?php
// Sample array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");

// Split alphabets array into chunks
print_r(array_chunk($alphabets, 2, true));
?>
Advertisements
Bootstrap UI Design Templates

Your Feedback:

We would love to hear from you, please drop us a line.