3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array = [ 'Name/First' => 'John', 'Name/Last' => 'Doe', 'Age' => 20, 'Address/Postal/City' => 'New York', 'Address/Postal/Zip' => 10003, 'Address/Billing/City' => 'Los Angeles', 'Phone' => 123456789, 'Foo/Bar' => 'test1', 'Foo/Bar/Foo2/Bar2' => 'test2', ]; $newarray = []; foreach($array as $path => $value) { $keys = array_filter(explode('/', $path)); $ref = &$newarray; foreach($keys as $level => $key) { if (!array_key_exists($key, $ref)) $ref[$key] = []; $ref = &$ref[$key]; if (isset($ref) && !is_array($ref)) { break; } } if (is_array($ref)) { $ref = $value; } } print_r($newarray);
Output for 7.4.26, 8.1.23 - 8.1.33, 8.2.10 - 8.2.29, 8.3.0 - 8.3.4, 8.3.6 - 8.3.27, 8.4.1 - 8.4.14
Array ( [Name] => Array ( [First] => John [Last] => Doe ) [Age] => 20 [Address] => Array ( [Postal] => Array ( [City] => New York [Zip] => 10003 ) [Billing] => Array ( [City] => Los Angeles ) ) [Phone] => 123456789 [Foo] => Array ( [Bar] => test1 ) )
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 ( [Name] => Array ( [First] => John [Last] => Doe ) [Age] => 20 [Address] => Array ( [Postal] => Array ( [City] => New York [Zip] => 10003 ) [Billing] => Array ( [City] => Los Angeles ) ) [Phone] => 123456789 [Foo] => Array ( [Bar] => test1 ) )

preferences:
93.61 ms | 409 KiB | 5 Q