Skip to content

Instantly share code, notes, and snippets.

@dkesberg
Created October 20, 2015 14:10
Show Gist options
  • Select an option

  • Save dkesberg/b7d3d4489b27e121728a to your computer and use it in GitHub Desktop.

Select an option

Save dkesberg/b7d3d4489b27e121728a to your computer and use it in GitHub Desktop.
Slice array in equal parts. For example array(10) into 3 parts => array(4), array(3), array(3)
<?php
function slice_equal($source, $columns) {
$count = count($source);
$perColumn = floor($count / $columns);
$overflow = $count % $columns;
// set start values
$sliceOffset = 0;
$sliceOverflow = ($overflow > 0) ? 1 : 0;
$sliceLength = $perColumn + $sliceOverflow;
$overflow--;
// slice up the source array
$return = [];
while (count($return) < $columns) {
$return[] = array_slice($source, $sliceOffset, $sliceLength);
// prepare for next slice
$sliceOffset += $sliceLength;
$sliceOverflow = ($overflow > 0) ? 1 : 0;
$sliceLength = $perColumn + $sliceOverflow;
$overflow--;
}
// return slices
return $return;
}
// example
$exampleSource = ['Belize', 'Canada', 'Cuba', 'Dominican Republic', 'El Salvador', 'Guatemala', 'Haiti', 'Honduras', 'Jamaica', 'Puerto Rico', 'USA'];
$slicedArray = slice_equal($exampleSource, 3);
print_r($slicedArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment