[PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8]
array_chunk — Split an array into chunks
Description
array_chunk[array $array
, int $length
, bool $preserve_keys
= false
]: array
Parameters
array
The array to work on
length
The size of each chunk
preserve_keys
When set to true
keys will be preserved. Default is false
which will reindex the chunk numerically
Return Values
Returns a multidimensional numerically indexed
array, starting with zero, with each dimension containing length
elements.
Errors/Exceptions
If length
is less than 1
, a ValueError will be thrown.
Changelog
8.0.0 | If length is less than 1 , a ValueError will be thrown now; previously, an error of level E_WARNING has been raised instead, and the function returned null .
|
Examples
Example #1 array_chunk[] example
The above example will output:
Array [ [0] => Array [ [0] => a [1] => b ] [1] => Array [ [0] => c [1] => d ] [2] => Array [ [0] => e ] ] Array [ [0] => Array [ [0] => a [1] => b ] [1] => Array [ [2] => c [3] => d ] [2] => Array [ [4] => e ] ]
azspot at gmail dot com ¶
15 years ago
Tried to use an example below [#56022] for array_chunk_fixed that would "partition" or divide an array into a desired number of split lists -- a useful procedure for "chunking" up objects or text items into columns, or partitioning any type of data resource. However, there seems to be a flaw with array_chunk_fixed — for instance, try it with a nine item list and with four partitions. It results in 3 entries with 3 items, then a blank array.
So, here is the output of my own dabbling on the matter:
Array
[
[0] => Array
[
[0] => Black Canyon City
[1] => Chandler
[2] => Flagstaff
[3] => Gilbert
[4] => Glendale
[5] => Globe
]
[1] => Array
[
[0] => Mesa
[1] => Miami
[2] => Phoenix
[3] => Peoria
[4] => Prescott
[5] => Scottsdale
]
[2] => Array
[
[0] => Sun City
[1] => Surprise
[2] => Tempe
[3] => Tucson
[4] => Wickenburg
]
]
suisuiruyi at aliyun dot com ¶
6 years ago
chunk array vertically
$arr = range[1, 19];
function array_chunk_vertical[$arr, $percolnum]{
$n = count[$arr];
$mod = $n % $percolnum;
$cols = floor[$n / $percolnum];
$mod ? $cols++ : null ;
$re = array[];
for[$col = 0; $col < $cols; $col++]{
for[$row = 0; $row < $percolnum; $row++]{
if[$arr]{
$re[$row][] = array_shift[$arr];
}
}
}
return $re;
}
$result = array_chunk_vertical[$arr, 6];
foreach[$result as $row]{
foreach[$row as $val]{
echo '['.$val.']';
}
echo '
';
}
/*
[1][7][13][19]
[2][8][14]
[3][9][15]
[4][10][16]
[5][11][17]
[6][12][18]
*/
Anonymous ¶
1 year ago
Most easy way split array to parts
Andrew Martin ¶
4 years ago
To reverse an array_chunk, use array_merge, passing the chunks as a variadic:
dustin at fivetechnology dot com ¶
6 years ago
Had need to chunk an object which implemented ArrayAccess Iterator Countable. array_chunk wouldn't do it. Should work for any list of things