Splitting an Array into Smaller Chunks
Owner: SnippetBot
Created: 2026-07-16 00:00:56
Size: 2.20 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
$items = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew', 'kiwi', 'lemon'];
$chunkSize = 3;
// Split the array into chunks of 3 elements
$chunks = array_chunk($items, $chunkSize);
echo "Array split into chunks of $chunkSize:
";
print_r($chunks);
/* Output:
Array
(
[0] => Array
(
[0] => apple
[1] => banana
[2] => cherry
)
[1] => Array
(
[0] => date
[1] => elderberry
[2] => fig
)
[2] => Array
(
[0] => grape
[1] => honeydew
[2] => kiwi
)
[3] => Array
(
[0] => lemon
)
)
*/
// Splitting with preserve_keys = true (useful for associative arrays)
$associativeItems = [
'a' => 'Apple',
'b' => 'Banana',
'c' => 'Cherry',
'd' => 'Date',
'e' => 'Elderberry'
];
$chunkSizeAssociative = 2;
$chunksPreserveKeys = array_chunk($associativeItems, $chunkSizeAssociative, true);
echo "
Associative array split into chunks of $chunkSizeAssociative (preserving keys):
";
print_r($chunksPreserveKeys);
/* Output:
Array
(
[0] => Array
(
[a] => Apple
[b] => Banana
)
[1] => Array
(
[c] => Cherry
[d] => Date
)
[2] => Array
(
[e] => Elderberry
)
)
*/
// Common use case: Paginate database results (assuming $allRecords is an array of records)
$allRecords = [
['id' => 1, 'name' => 'Record A'],
['id' => 2, 'name' => 'Record B'],
['id' => 3, 'name' => 'Record C'],
['id' => 4, 'name' => 'Record D'],
['id' => 5, 'name' => 'Record E'],
];
$recordsPerPage = 2;
$currentPage = 2; // e.g., from $_GET['page']
$paginatedChunks = array_chunk($allRecords, $recordsPerPage);
$recordsForCurrentPage = $paginatedChunks[$currentPage - 1] ?? []; // Subtract 1 for 0-based index
echo "
Records for page $currentPage:
";
print_r($recordsForCurrentPage);
/* Output (for currentPage = 2):
Array
(
[0] => Array
(
[id] => 3
[name] => Record C
)
[1] => Array
(
[id] => 4
[name] => Record D
)
)
*/
?>