php uses the array_chunk function to split an array into multiple arrays

  • 2021-11-10 09:01:36
  • OfStack

In php, you can use array_chunk to divide an array into several arrays.

Array


$array = ['name' => 'tom', 'age' => 20, 3, 4, 5, 'a', 'b'];

Divide every 3 into 1 group


$chunk_result = array_chunk($array, 3);

Results


Array
(
 [0] => Array
  (
   [0] => tom
   [1] => 20
   [2] => 3
  )
 [1] => Array
  (
   [0] => 4
   [1] => 5
   [2] => a
  )
 [2] => Array
  (
   [0] => b
  )
)

If the number is insufficient, the last array is not 1 and is determined to be 3

If you want to preserve the key value, you can set the third parameter to true


$chunk_result = array_chunk($array, 3, true);

Results


Array
(
 [0] => Array
  (
   [name] => tom
   [age] => 20
   [0] => 3
  )
 [1] => Array
  (
   [1] => 4
   [2] => 5
   [3] => a
  )
 [2] => Array
  (
   [4] => b
  )
)

Experience

The hole in using array_chunk comparison is that if the array is too large, array_chunk is likely to cause a memory overflow, and an error like this is reported: Allowed memory size of 134217728 bytes exhausted.


Related articles: