3v4l.org

run code in 300+ PHP versions simultaneously
<?php function createArrayMap(iterable $input, string $indexKey, ?string $valueKey = null): array { $map = []; foreach ($input as $obj) { $arr = $obj; $mapKey = $arr[$indexKey]; $value = $valueKey !== null ? $arr[$valueKey] : $obj; if (!array_key_exists($mapKey, $map)) { $map[$mapKey] = []; } $map[$mapKey][] = $value; } return $map; } $data = [ [ 'key' => 'first', 'name' => 'Foo' ], [ 'key' => 'second', 'name' => 'Bar' ], null ]; var_dump(createArrayMap($data, 'key'));
Output for 8.0.0 - 8.0.13, 8.1rc1 - rc3
Warning: Trying to access array offset on value of type null in /in/bRhDB on line 10 array(3) { ["first"]=> array(1) { [0]=> array(2) { ["key"]=> string(5) "first" ["name"]=> string(3) "Foo" } } ["second"]=> array(1) { [0]=> array(2) { ["key"]=> string(6) "second" ["name"]=> string(3) "Bar" } } [""]=> array(1) { [0]=> NULL } }
Output for 7.4.0 - 7.4.26
Notice: Trying to access array offset on value of type null in /in/bRhDB on line 10 array(3) { ["first"]=> array(1) { [0]=> array(2) { ["key"]=> string(5) "first" ["name"]=> string(3) "Foo" } } ["second"]=> array(1) { [0]=> array(2) { ["key"]=> string(6) "second" ["name"]=> string(3) "Bar" } } [""]=> array(1) { [0]=> NULL } }
Output for 7.3.0 - 7.3.33
array(3) { ["first"]=> array(1) { [0]=> array(2) { ["key"]=> string(5) "first" ["name"]=> string(3) "Foo" } } ["second"]=> array(1) { [0]=> array(2) { ["key"]=> string(6) "second" ["name"]=> string(3) "Bar" } } [""]=> array(1) { [0]=> NULL } }

preferences:
36.83 ms | 538 KiB | 14 Q