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.

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.

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

This produces the following output.

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
 )
 
)

 

Comments

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

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.