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 git.master_jit, git.master, rfc.property-hooks
All tests passed

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
86 ms | 405 KiB | 5 Q