3v4l.org

run code in 300+ PHP versions simultaneously
<?php interface ArrayKeyable { public function toArrayKey(): string|int; } final class MyObject implements ArrayKeyable { public function __construct( public readonly int $id, public readonly string $name, ) {} public function toArrayKey(): string { return $this->name; } } $objects = []; $data = [[1, 'Jane'], [2, 'John'], [3, 'Jake'], [4, 'Jane']]; foreach($data as [$id, $name]) { $object = new MyObject($id, $name); $objects[$object->toArrayKey()][] = $object; // would turn into $objects[$object][] = $object; } var_dump($objects);
Output for 8.2.5
array(3) { ["Jane"]=> array(2) { [0]=> object(MyObject)#1 (2) { ["id"]=> int(1) ["name"]=> string(4) "Jane" } [1]=> object(MyObject)#4 (2) { ["id"]=> int(4) ["name"]=> string(4) "Jane" } } ["John"]=> array(1) { [0]=> object(MyObject)#2 (2) { ["id"]=> int(2) ["name"]=> string(4) "John" } } ["Jake"]=> array(1) { [0]=> object(MyObject)#3 (2) { ["id"]=> int(3) ["name"]=> string(4) "Jake" } } }

preferences:
161.07 ms | 1395 KiB | 8 Q