3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Foo { private $groupId; private $value; function __construct($groupId, $value) { $this->groupId = $groupId; $this->value = $value; } function getGroupId() { return $this->groupId; } }; $foos = [ new Foo(1, 'Bar'), new Foo(1, 'Ban'), new Foo(1, 'Bak'), new Foo(2, 'Gas'), new Foo(2, 'Gar'), ]; var_dump(array_reduce($foos, function($carry, $item){ if(!isset($carry[$item->getGroupId()])) { $carry[$item->getGroupId()] = []; } $carry[$item->getGroupId()][] = $item; return $carry; }, []));
Output for 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
array(2) { [1]=> array(3) { [0]=> object(Foo)#1 (2) { ["groupId":"Foo":private]=> int(1) ["value":"Foo":private]=> string(3) "Bar" } [1]=> object(Foo)#2 (2) { ["groupId":"Foo":private]=> int(1) ["value":"Foo":private]=> string(3) "Ban" } [2]=> object(Foo)#3 (2) { ["groupId":"Foo":private]=> int(1) ["value":"Foo":private]=> string(3) "Bak" } } [2]=> array(2) { [0]=> object(Foo)#4 (2) { ["groupId":"Foo":private]=> int(2) ["value":"Foo":private]=> string(3) "Gas" } [1]=> object(Foo)#5 (2) { ["groupId":"Foo":private]=> int(2) ["value":"Foo":private]=> string(3) "Gar" } } }

preferences:
132.33 ms | 410 KiB | 5 Q