Columnize an Array with PHP

January 22, 2011
This function uses an array to output a table with the elements divided into columns. The test code and results are shown below.

Download Original
  1. <?PHP
  2. function columnize($data,$maxrows=10)
  3. {
  4. /*
  5. Columnize - Robert Lerner - 2011.01.13.21.23 - www.Robert-Lerner.com/columnize.php
  6.  
  7. Use:
  8. STRING = columnize(ARRAY[MIXED],INTEGER);
  9. Array may not be multidimensional.
  10. Sorts array elements into columns, data + <br />.
  11.  
  12. */
  13. if (!is_array($data))
  14. {
  15. trigger_error("Data provided to columnize was not an array.",E_USER_ERROR);
  16. }
  17. if (!is_numeric($maxrows))
  18. {
  19. trigger_error("MaxRows provided to columnize was not numeric.",E_USER_ERROR);
  20. }
  21.  
  22. $ColumnID = 0;
  23. for ($DataCount=0;$DataCount<=count($data);$DataCount++)
  24. {
  25. if ($DataCount%$maxrows==0)
  26. {
  27. $ColumnID++;
  28. }
  29. $Col[$ColumnID] .= $data[$DataCount] . "<br />";
  30. }
  31. $RetVal = "<table><tr>";
  32. for ($i=1;$i<=$ColumnID;$i++)
  33. {
  34. $RetVal .= "<td valign='top'>" . $Col[$i] . "</td>";
  35. }
  36. $RetVal .= "</tr></table>";
  37. RETURN $RetVal;
  38. }


This example uses the function after generating an array with the following elements:
$arr[0] = 0;
$arr[1] = 1;
etc...

for ($i=0;$i<=49;$i++)
     {
     $arr[$i] = $i;
     }
echo columnize($arr,2);


Output

0
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



Changing the second parameter of columnize to 5, and then 10 below:

Output

0
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



0
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

Name:

No comments yet! Be the first!