Skip to content

Instantly share code, notes, and snippets.

@dlundgren
Last active August 29, 2015 14:04
Show Gist options
  • Save dlundgren/d5c98c61e40580d889c9 to your computer and use it in GitHub Desktop.
Save dlundgren/d5c98c61e40580d889c9 to your computer and use it in GitHub Desktop.
Partitions an array. Similar to array_chunk but goes through the array linearly
<?php
/**
* Partitions the array in a linear fashion.
*
* This is similar to array_chunk
*
* @param array $ary The array to partition
* @param int $partitions How many partitions should the array be split into.
* Default is to calculate off of the input array length
* @return array
*/
function array_partition(array $ary, $partitions = null) {
$ret = array();
$keys = array_keys($ary);
$length = count($keys);
if ($partitions === null) {
$partitions = round($length / 2);
}
for ($i = 0; $i < $length; ++$i){
$ret[$i % $partitions][] = $ary[$keys[$i]];
}
return $ret;
}
@dlundgren
Copy link
Author

// [ [1,4], [2,5], [3,6] ]
array_partition([1,2,3,4,5,6], 3);
array_partition([1,2,3,4,5,6]);    

// [ [1,3,5], [2,4,6] ]
array_partition([1,2,3,4,5,6], 2); 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment