Split An Array Into Smaller Parts In PHP

Saturday, May 17, 2008 - 16:00

Splitting an array into sections might be useful for setting up a calendar or pagination on a site. Either way there are numerous ways to do this but the following seems to be the quickest and most reliable method.

1
2
3
4
5
6
7
8
9
10
11
12
13
function sectionArray($array, $step)
{
 $sectioned = array();
 
 $k = 0;
 for ( $i=0;$i < count($array); $i++ ) {
  if ( !($i % $step) ) {
   $k++;
  }
  $sectioned[$k][] = $array[$i];
 }
 return $sectioned;
}

Run the function by passing it an array, in this case I am going to split the alphabet into 5 arrays of 5 letters.

1
2
3
$array = range('a','z'); // create an array from a to z
 
echo '<pre>'.print_r(ArraySplitIntoParts_Shorter($array,5),true).'
';

This produces the following output.

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
Array
(
 [1] => Array
 (
  [0] => a
  [1] => b
  [2] => c
  [3] => d
  [4] => e
 )
 
 [2] => Array
 (
  [0] => f
  [1] => g
  [2] => h
  [3] => i
  [4] => j
 )
 
 [3] => Array
 (
  [0] => l
  [1] => m
  [2] => n
  [3] => o
  [4] => p
 )
 
 [4] => Array
 (
  [0] => q
  [1] => r
  [2] => s
  [3] => t
  [4] => u
 )
 
 [5] => Array
 (
  [0] => v
  [1] => w
  [2] => x
  [3] => y
  [4] => z
 )
 
)
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

Thank you! I guess at that moment did not exist function array_chunk, it makes the same thing :)

Add new comment