Home »
PHP
PHP Array array_chunk() Function (With Examples)
In this tutorial, we will learn about the PHP array_chunk() function with its usage, syntax, parameters, return value, and examples.
By IncludeHelp Last updated : December 31, 2023
PHP array_chunk() Function
The array_chunk() function is an array function, it is used to split a given array in number of array (chunks of arrays).
Syntax
The syntax of the array_chunk() function:
array_chunk(array_name, size, [preserve_keys]) : array
Parameters
The parameters of the array_chunk() function:
- array_name is the main array, which we have to convert into array chunks.
- size is the number of arrays to be converted.
- preserve_keys is an optional parameter and its default value is false. If it is true keys will be preserved and if it is “false” the keys of the arrays will be re-indexed in sub arrays.
Return Value
The return type of this method is array, it returns a multidimensional numerically indexed array, starting with zero, with each dimension containing length elements. [Source]
Sample Input/Output
Input:
$arr = array("New Delhi", "Mumbai", "Chennai", "Pune", "Gwalior");
Output:
Array
(
[0] => Array
(
[0] => New Delhi
[1] => Mumbai
[2] => Chennai
)
[1] => Array
(
[0] => Pune
[1] => Gwalior
)
)
PHP array_chunk() Function Example 1
<?php
$arr = array("New Delhi", "Mumbai", "Chennai", "Pune", "Gwalior");
print ("Original array is...\n");
print_r ($arr);
$arr1 = array_chunk($arr, 3);
print ("array (size: 3) is...\n");
print_r ($arr1);
?>
Output
The output of the above example is:
Original array is...
Array
(
[0] => New Delhi
[1] => Mumbai
[2] => Chennai
[3] => Pune
[4] => Gwalior
)
array (size: 2) is...
Array
(
[0] => Array
(
[0] => New Delhi
[1] => Mumbai
[2] => Chennai
)
[1] => Array
(
[0] => Pune
[1] => Gwalior
)
)
PHP array_chunk() Function Example 2: With preserved – "true"
<?php
$arr = array("New Delhi", "Mumbai", "Chennai", "Pune", "Gwalior");
print ("Original array is...\n");
print_r ($arr);
$arr1 = array_chunk($arr, 3, true);
print ("array (size: 2) is...\n");
print_r ($arr1);
?>
Output
The output of the above example is:
Original array is...
Array
(
[0] => New Delhi
[1] => Mumbai
[2] => Chennai
[3] => Pune
[4] => Gwalior
)
array (size: 2) is...
Array
(
[0] => Array
(
[0] => New Delhi
[1] => Mumbai
[2] => Chennai
)
[1] => Array
(
[3] => Pune
[4] => Gwalior
)
)
See the output 1 & Output 2, in first output sub arrays are re-indexed while in output 2 arrays are not re-indexed.