PHP array_chunk() Function

Example

Split the array into an array with two elements:

<?php
$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
print_r(array_chunk($cars,2));
?>

Run Instance

Definition and Usage

The array_chunk() function splits the array into new array blocks.

Among which the number of units in each array is determined by size Parameter determines. The number of units in the last array may be a few less.

Optional Parameters preserve_key Is a boolean value that specifies whether the elements of the new array have the same keys as the original array (used for associative arrays) or new numeric keys starting from 0 (used for indexed arrays). The default is to assign new keys.

Syntax

array_chunk(array,size,preserve_key);
Parameter Description
array Required. Specifies the array to be used.
size Required. Integer value, specifying how many elements each new array contains.
preserve_key

Optional. Possible values:

  • true - Retain the key names in the original array.
  • false - Default. Each result array uses a new array index starting from zero.

Technical Details

Return Value: Returns a multidimensional indexed array, starting from 0, each dimension contains size elements.
PHP Version: 4.2+

More Examples

Example 1

Split the array into an array with two elements, and retain the key names in the original array:

<?php
$age=array("Bill"=>"60","Steve"=>"56","Mark"=>"31","David"=>"35");
print_r(array_chunk($age,2,true));
?>

Run Instance