Current Location: Home> Function Categories> array_chunk

array_chunk

Split the array into blocks
Name:array_chunk
Category:Array
Programming Language:php
One-line Description:Split an array into new array chunks.

Definition and usage

array_chunk() function divides the array into new array chunks.

The number of units in each array is determined by the size parameter. The number of units in the last array may be fewer.

The optional parameter preserve_key is a Boolean value that specifies whether the elements of the new array have the same key as the original array (for associative arrays), or a new numeric key starting from 0 (for indexing arrays). The default is to assign a new key.

Example

Example 1

Split the array into an array with two elements:

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

Try it yourself

Example 2

Split the array into an array with two elements and preserve 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 ) ) ;
?>

Try it yourself

grammar

 array_chunk ( array , size , preserve_key ) ;
parameter describe
array Required. Specifies the array to be used.
size Required. Integer value, specify how many elements each new array contains.
preserve_key

Optional. Possible values:

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