Usage and precautions of php array_chunk of function

  • 2021-12-13 07:40:34
  • OfStack

This article illustrates the usage and precautions of php array_chunk () function. Share it for your reference, as follows:

Definition and usage

array_chunk() Function to split an array into new array blocks.

Where the number of cells in each array is determined by the size parameter. The number of cells in the last 1 array may be several fewer.

The optional parameter preserve_key is a Boolean value (default false) 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 a new key.

For example:


$arr = [1,2,3,4,5,6,7,8,9,10];
$arr = array_chunk($arr,2);
// Then:  $arr = [[1,2],[3,4],[5,6],[7,8],[9,10]];
print_r($arr);

Run results:

Array
(
[0] = > Array
(
[0] = > 1
[1] = > 2
)

[1] = > Array
(
[0] = > 3
[1] = > 4
)

[2] = > Array
(
[0] = > 5
[1] = > 6
)

[3] = > Array
(
[0] = > 7
[1] = > 8
)

[4] = > Array
(
[0] = > 9
[1] = > 10
)

)


$arr = [0=>'lily',1=>'lala',2=>'yaya',3=>'nini',4=>'maya',5=>'lant'];
$arr = array_chunk($arr,2,true);
// Then: $arr = [[0=>'lily',1=>'lala'],[2=>'yaya',3=>'nini'],[4=>'maya',5=>'lant']];
print_r($arr);

Run results:

Array
(
[0] = > Array
(
[0] = > lily
[1] = > lala
)

[1] = > Array
(
[2] = > yaya
[3] = > nini
)

[2] = > Array
(
[4] = > maya
[5] = > lant
)

)

If the third parameter is false. New keys will be assigned, all starting from 0.

It is worth noting that when using array_chunk() Split the array, insert the database, if the split array is not equal, it may cause the database to increase id discontinuous, so there is a need to increase id continuous, try to make array_chunk() The new array is divided into equal parts to avoid some problems.

For more readers interested in PHP related contents, please check the special topics of this site: "PHP Array (Array) Operation Skills Encyclopedia", "php Sorting Algorithm Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary" and "PHP Common Traversal Algorithms and Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: