Friday, 10 August 2018

Split An Array Into Smaller Parts In PHP

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. function sectionArray($array, $step)
  2. {
  3. $sectioned = array();
  4.  
  5. $k = 0;
  6. for ( $i=0;$i < count($array); $i++ ) {
  7. if ( !($i % $step) ) {
  8. $k++;
  9. }
  10. $sectioned[$k][] = $array[$i];
  11. }
  12. return $sectioned;
  13. }
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. $array = range('a','z'); // create an array from a to z
  2.  
  3. echo '<pre>'.print_r(ArraySplitIntoParts_Shorter($array,5),true).'</pre>';
This produces the following output.
  1. Array
  2. (
  3. [1] => Array
  4. (
  5. [0] => a
  6. [1] => b
  7. [2] => c
  8. [3] => d
  9. [4] => e
  10. )
  11.  
  12. [2] => Array
  13. (
  14. [0] => f
  15. [1] => g
  16. [2] => h
  17. [3] => i
  18. [4] => j
  19. )
  20.  
  21. [3] => Array
  22. (
  23. [0] => l
  24. [1] => m
  25. [2] => n
  26. [3] => o
  27. [4] => p
  28. )
  29.  
  30. [4] => Array
  31. (
  32. [0] => q
  33. [1] => r
  34. [2] => s
  35. [3] => t
  36. [4] => u
  37. )
  38.  
  39. [5] => Array
  40. (
  41. [0] => v
  42. [1] => w
  43. [2] => x
  44. [3] => y
  45. [4] => z
  46. )
  47.  
  48. )

0 comments:

Post a Comment