Skip to content

Instantly share code, notes, and snippets.

@blar
Created February 13, 2014 19:29
Show Gist options
  • Select an option

  • Save blar/8982098 to your computer and use it in GitHub Desktop.

Select an option

Save blar/8982098 to your computer and use it in GitHub Desktop.
array_partition
<?php
function array_partition($array, $callback, $preserveKeys = false) {
$partitions = array();
foreach($array as $key => $value) {
$partitionName = $callback($value, $key);
if(!array_key_exists($partitionName, $partitions)) {
$partitions[$partitionName] = array();
}
if($preserveKeys) {
$partitions[$partitionName][$key] = $value;
}
else {
$partitions[$partitionName][] = $value;
}
}
return $partitions;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment