public static assertValidArrayKey ( mixed $key, string $callee ) | ||
$key | mixed | |
$callee | string |
public static function assertValidArrayKey($key, $callee)
{
$keyTypes = ['NULL', 'string', 'integer', 'double', 'boolean'];
$keyType = gettype($key);
if (!in_array($keyType, $keyTypes, true)) {
throw new static(sprintf('%s(): callback returned invalid array key of type "%s". Expected %4$s or %3$s', $callee, $keyType, array_pop($keyTypes), join(', ', $keyTypes)));
}
}
/** * Groups a collection by index returned by callback. * * @param Traversable|array $collection * @param callable $callback * @return array */ 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__); if (!isset($groups[$groupKey])) { $groups[$groupKey] = []; } $groups[$groupKey][$index] = $element; } return $groups; }