Home > Article > Backend Development > How to use php array_chunk function
php array_chunk function is used to split an array into new array chunks. The syntax is array_chunk(array, size, preserve_key). The parameter array is required and specifies the array to be used; size is required and is an integer value that specifies how many elements each new array contains.
#php array_chunk function how to use?
Function: Split the array into new array blocks.
Syntax:
array_chunk(array,size,preserve_key)
Parameters:
array Required. Specifies the array to use.
size Required. An integer value specifying how many elements each new array contains.
preserve_key Optional. Possible values: true - retain the key names from the original array. false - default. Each result array uses a new array index starting from zero.
Instructions:
Split the array into new array blocks. The number of cells in each array is determined by the size parameter. The last array may have a few fewer elements.
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 indexed arrays) . The default is to assign new keys.
php array_chunk() function usage example 1
<?php $class=array("灭绝","无忌","西门","peter"); print_r(array_chunk($class,2)); ?>
Output:
Array ( [0] => Array ( [0] => 灭绝 [1] => 无忌 ) [1] => Array ( [0] => 西门 [1] => peter ) )
php array_chunk() function usage example 2
<?php $age=array("灭绝"=> 25,"无忌" => 20,"西门" => 27,"peter" => 37); print_r(array_chunk($age,2,true)); ?>
Output:
Array ( [0] => Array ( [灭绝] => 25 [无忌] => 20 ) [1] => Array ( [西门] => 27 [peter] => 37 ) )
The above is the detailed content of How to use php array_chunk function. For more information, please follow other related articles on the PHP Chinese website!