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.1.30 - 8.1.33, 8.2.5 - 8.2.29, 8.3.5 - 8.3.28, 8.4.1 - 8.4.14, 8.5.0
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" } } }
Output for 8.4.15
/bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.35' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.34' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15)
Process exited with code 1.

preferences:
81.17 ms | 408 KiB | 5 Q