array_chunk() splits one array into smaller arrays of a chosen size. The optional third argument controls whether original keys are preserved.
$items = ['A', 'B', 'C', 'D', 'E'];
$groups = array_chunk($items, 2);
print_r($groups);Chunking is useful for pagination-like groups, rows, batches and other fixed-size processing.
$input=array('One','Two','Three','Four','Five');
$output=array_chunk($input,2);
echo print_r($output);
echo "<br><b>$key -> $val</b> <br>";
foreach ($val as $key1 => $val1) {
echo "$key1 -> $val1 <br>";
}
}
Output is here
Array ( [0] => Array ( [0] => One [1] => Two ) [1] => Array ( [0] => Three [1] => Four ) [2] => Array ( [0] => Five ) ) 1
0 -> Array
0 -> One
1 -> Two
1 -> Array
0 -> Three
1 -> Four
2 -> Array
0 -> Five
Syntax
array_chunk ($input_array , int $size [, bool $preserve_keys = FALSE ] )
| Parameter | DESCRIPTION |
|---|---|
| $input_array | Required : Input array to break |
| $size | Required : INT , Number of elements in output array or size of broken arrays. |
| $preserve_keys | Optional :Boolean , default value is FALSE to reindex the output chunk numerically. TRUE : The keys of $input_array are preserved. |
$input=array('One','Two','Three','Four','Five');
$output=array_chunk($input,2,true);
echo print_r($output);
echo "<br><b>$key -> $val</b> <br>";
foreach ($val as $key1 => $val1) {
echo "$key1 -> $val1 <br>";
}
}
Output is here
Array ( [0] => Array ( [0] => One [1] => Two ) [1] => Array ( [2] => Three [3] => Four ) [2] => Array ( [4] => Five ) ) 1
0 -> Array
0 -> One
1 -> Two
1 -> Array
2 -> Three
3 -> Four
2 -> Array
4 -> Five
Joining Two Arrays by array_merge
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.