forked from lstrojny/functional-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroup.php
More file actions
48 lines (37 loc) · 1.16 KB
/
Group.php
File metadata and controls
48 lines (37 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
/**
* @package Functional-php
* @author Lars Strojny <lstrojny@php.net>
* @copyright 2011-2021 Lars Strojny
* @license https://opensource.org/licenses/MIT MIT
* @link https://github.com/lstrojny/functional-php
*/
namespace Functional;
use Functional\Exceptions\InvalidArgumentException;
use Traversable;
/**
* Groups a collection by index returned by callback.
*
* @param Traversable|array $collection
* @param callable $callback
* @return array
* @no-named-arguments
*/
function group($collection, callable $callback)
{
InvalidArgumentException::assertCollection($collection, __FUNCTION__, 1);
$groups = [];
foreach ($collection as $index => $element) {
$groupKey = $callback($element, $index, $collection);
InvalidArgumentException::assertValidArrayKey($groupKey, __FUNCTION__);
// Avoid implicit conversion, since float numbers cannot be used as array keys
if (\is_numeric($groupKey)) {
$groupKey = (int) $groupKey;
}
if (!isset($groups[$groupKey])) {
$groups[$groupKey] = [];
}
$groups[$groupKey][$index] = $element;
}
return $groups;
}