Created
October 20, 2015 14:10
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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