PHP: Array Slice splitting array into chunks

In PHP we can able to slice an Array into small chunks. To chunk array, there is a function called array_slice(). This function will accept splitting array with Limit and offset of the slice. It will split array into given limit from the offset of starting.

Syntax:
$splitArray = array_slice(ARRAY, OFFSET, LIMIT);

Example:

// Full array contains a list of values.
$fullArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
 
// Split array of size 5, starts from 0 index.
$splitArray1 = array_slice($fullArray, 0, 5);
print_r($splitArray1);
Array
(
  [0] => 1
  [1] => 2
  [2] => 3
  [3] => 4
  [4] => 5
)
 
// Split array of size 10, starts from 10 index.
$splitArray1 = array_slice($fullArray, 10, 10);
print_r($splitArray1);
Array
(
  [0] => 11
  [1] => 12
  [2] => 13
  [3] => 14
  [4] => 15
  [5] => 16
  [6] => 17
  [7] => 18
  [8] => 19
  [9] => 20
)

 

Category: