PHP array_chunk() Function
Example
Split the array into arrays with two elements:
<?php $cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel"); print_r(array_chunk($cars,2)); ?>
Definition and Usage
The array_chunk() function splits the array into new array blocks.
Where the number of units in each array is determined by size Parameter decides. 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);
Parameters | Description |
---|---|
array | Required. Specifies the array to be used. |
size | Required. Integer value, specifies how many elements each new array contains. |
preserve_key |
Optional. Possible values:
|
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 arrays with two elements, while preserving the original array keys:
<?php $age=array("Bill"=>"60","Steve"=>"56","Mark"=>"31","David"=>"35"); print_r(array_chunk($age,2,true)); ?>