3v4l.org

run code in 300+ PHP versions simultaneously
<?php $person = [ 'id' => '123', 'name' => 'John Doe', 'relationship_status' => 'Married', 'work_profession' => 'Teacher', 'work_salary' => '1500', 'work_status' => 'Working', 'work_place' => 'Lorem City School', 'from_province' => 'Dolor Sit Province', 'from_city_name' => 'Ipsum City', 'from_city_address' => 'Some Rd. 1337' ]; function reShapeArray(array $arr): array { $return = []; foreach ($arr as $key => $value) { $firstUnderscore = strpos($key, '_'); if ($firstUnderscore === false) { // already at the lowest level, simply return as is $return[$key] = $value; } else { // there's an underscore, dig into this [$top, $sub] = explode('_', $key, 2); $return[$top] = array_merge_recursive($return[$top] ?? [], reShapeArray([$sub => $value])); } } return $return; } function mergeSingleElementArrays(array $arr): array { $return = []; foreach ($arr as $key => $value) { if (is_array($value) && count($value) === 1) { $subKey = array_key_first($value); $return["{$key}_{$subKey}"] = $value[$subKey]; } else { $return[$key] = $value; } } return $return; } $tests = [ 'deep array with single prefixed key' => [ ['a_b_c_d' => 'foo', 'a_b_e' => 'bar',], ['a_b' => ['c' => ['d' => 'foo'], 'e' => 'bar']], ], 'single prefixed key' => [['a_b' => 'foo'], ['a_b' => 'foo']], 'standard' => [ $person, [ 'id' => '123', 'name' => 'John Doe', 'relationship_status' => 'Married', 'work' => [ 'profession' => 'Teacher', 'salary' => '1500', 'status' => 'Working', 'place' => 'Lorem City School', ], 'from' => [ 'province' => 'Dolor Sit Province', 'city' => [ 'name' => 'Ipsum City', 'address' => 'Some Rd. 1337', ], ], ], ], ]; $errors = []; foreach ($tests as $name => [$input, $expected]) { $result = reShapeArray($input); $foo = mergeSingleElementArrays($result); if ($foo !== $expected) { $errors[] = "Test '$name' failed: got " . json_encode($foo) . ' vs expected ' . json_encode($expected); } } if ($errors) { var_dump($errors); } else { echo "All tests passed\n"; }
Output for 8.1.27 - 8.1.33, 8.2.14 - 8.2.29, 8.3.1 - 8.3.28, 8.4.1 - 8.4.14, 8.5.0 - 8.5.1
All tests passed
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:
52.41 ms | 407 KiB | 5 Q