Dividing an array into smaller group in PHP using array_chunk function

There are times when we need to divide an array into smaller chunks, for the same in PHP we have a build in function called array_chunk. The array_chunk() function in PHP takes 3 arguments , first argument is the original array which need to be divided into smaller groups, second argument is array chunk size, third parameter takes boolean values(true/false), if we need to keep original array index/key as is. Code


$array_var = [10=>"apple1", 11=>"apple2", 12=>"apple3", 13=>"apple4"];

$result = array_chunk($array_var, 2);

print_r($result);

Output

Array ( 
    [0] => Array ( 
        [0] => apple1 
        [1] => apple2 
    ) 
    [1] => Array ( 
        [0] => apple3 
        [1] => apple4 
    )
)
Code to keep original index as is

$array_var = [10=>"apple1", 11=>"apple2", 12=>"apple3", 13=>"apple4"];

$result = array_chunk($array_var, 2, true);

print_r($result);

Output

Array ( 
    [0] => Array ( 
        [10] => apple1 
        [11] => apple2 
    ) 
    [1] => Array ( 
        [12] => apple3 
        [13] => apple4 
    )
)