DEV Community

Cover image for Uses of array_chunk function
Istiaq Nirab
Istiaq Nirab

Posted on

Uses of array_chunk function

array_chunk() is a build function in PHP.

Using this function, one or more new arrays are created with values of arrays. This function usually has 3 parameters.
But it is mandatory to use 2.

  • array – [array from which to extract values]
  • size – [key number of new arrays]
  • preserve_keys - [This value is FALSE by default, if TRUE, it will insert new arrays inside a new array]

Example – 1 :

<?php
    $array = array('a', 'b', 'c', 'd', 'e');
    print_r(array_chunk($array, 6));
?>
Enter fullscreen mode Exit fullscreen mode

Result :

Array (     
 [0] => Array (             
   [0] => a             
   [1] => b             
   [2] => c             
   [3] => d             
   [4] => e         
  ) 
)
Enter fullscreen mode Exit fullscreen mode

Example – 2 :

<?php
    $array = array('a', 'b', 'c', 'd', 'e');
    print_r(array_chunk($array, 2, true));
?>
Enter fullscreen mode Exit fullscreen mode

Result :

Array (     
 [0] => Array (
   [0] => a             
   [1] => b         
 )
 [1] => Array (
   [2] => c
   [3] => d
 )
 [2] => Array (
   [4] => e
  )
)
Enter fullscreen mode Exit fullscreen mode

Thanks 😊

Read Bangla :- https://nirab.xyz/post/uses-of-array_chunk-function/

Top comments (0)