3v4l.org

run code in 300+ PHP versions simultaneously
<?php ## the user "class" class Foo { public int $id; public string $foo; public ?string $group = null; public function __construct(int $id, string $foo) { $this->id = $id; $this->foo = $foo; } } ## users db result $users_array = [ new Foo(999, 'abc'), new Foo(4, 'abc'), new Foo(5, 'xyz'), new Foo(8, 'xxx') ]; ## get IDs and build index $index = []; $ids = array_reduce($users_array, function(?array $ids, Foo $object) use(&$index) { $ids[] = $object->id; $index[$object->id] = $object; return $ids; }); ### Groups, fetched from SQL $groups = [ [ 'id' => 999, 'group' => 'group1'], [ 'id' => 8, 'group' => 'group2'], [ 'id' => 4, 'group' => 'group3'], ]; ### stiching foreach ($groups as $row) { $index[$row['id']]->group = $row['group']; } ## now the original array of users have their "group" property populated from the groups query var_dump($users_array);
Output for 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
array(4) { [0]=> object(Foo)#1 (3) { ["id"]=> int(999) ["foo"]=> string(3) "abc" ["group"]=> string(6) "group1" } [1]=> object(Foo)#2 (3) { ["id"]=> int(4) ["foo"]=> string(3) "abc" ["group"]=> string(6) "group3" } [2]=> object(Foo)#3 (3) { ["id"]=> int(5) ["foo"]=> string(3) "xyz" ["group"]=> NULL } [3]=> object(Foo)#4 (3) { ["id"]=> int(8) ["foo"]=> string(3) "xxx" ["group"]=> string(6) "group2" } }
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 array(4) { [0]=> object(Foo)#1 (3) { ["id"]=> int(999) ["foo"]=> string(3) "abc" ["group"]=> string(6) "group1" } [1]=> object(Foo)#2 (3) { ["id"]=> int(4) ["foo"]=> string(3) "abc" ["group"]=> string(6) "group3" } [2]=> object(Foo)#3 (3) { ["id"]=> int(5) ["foo"]=> string(3) "xyz" ["group"]=> NULL } [3]=> object(Foo)#4 (3) { ["id"]=> int(8) ["foo"]=> string(3) "xxx" ["group"]=> string(6) "group2" } }
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33
Parse error: syntax error, unexpected 'int' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in /in/KQ33q on line 5
Process exited with code 255.

preferences:
159.37 ms | 402 KiB | 182 Q