3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php function initValueIfNotSet($target, $levels = array()) { //$merge = ['WorkRecord' => ['Hours' => '']]; $merge = []; for ($i = count($levels) - 1; $i >= 0; $i--) { $current = $levels[$i]; $merge = empty($merge) ? [$current => ''] : [$current => $merge]; } //return $target + $merge; return array_merge_recursive($target, $merge); } $user = ['Details' => ['Name' => 'Kokot'], 'WorkRecord' => ['Time' => ['Minutes' => 2]]]; var_dump($user); $user = initValueIfNotSet($user, ['WorkRecord', 'Time', 'Hours']); var_dump($user);
based on Ggtqc
Output for 5.6.0 - 5.6.30, hhvm-3.12.14 - 3.17.3, 7.0.0 - 7.3.0beta1
array(2) { ["Details"]=> array(1) { ["Name"]=> string(5) "Kokot" } ["WorkRecord"]=> array(1) { ["Time"]=> array(1) { ["Minutes"]=> int(2) } } } array(2) { ["Details"]=> array(1) { ["Name"]=> string(5) "Kokot" } ["WorkRecord"]=> array(1) { ["Time"]=> array(2) { ["Minutes"]=> int(2) ["Hours"]=> string(0) "" } } }