17th May 2008 - 3 minutes read time
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.