3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php function setValueInNestedArray(&$array, $path, $value, $delimiter = '.'){ $pathSegments = explode($delimiter, $path); $currentNode = &$array; foreach($pathSegments as $pathSegment) { if(!is_array($currentNode[$pathSegment])) { $currentNode[$pathSegment] = []; } $currentNode = &$currentNode[$pathSegment]; } $currentNode = $value; } function getValueInNestedArray($array, $path, $defaultValue, $delimiter = '.'){ $pathSegments = explode($delimiter, $path); $pathExists = true; $currentNode = &$array; foreach($pathSegments as $pathSegment) { if(is_array($currentNode[$pathSegment])) { $currentNode = &$currentNode[$pathSegment]; } else { $pathExists = false; } } return $pathExists ? $currentNode : $defaultValue; } $arr =[]; setValueInNestedArray($arr, 'a.b.c.d', 'e'); print(1); print_r($arr); print(2); print_r(getValueInNestedArray($arr, 'a', null)); print(3); print_r(getValueInNestedArray($arr, 'a.b.c.d', null)); print(4); print_r(getValueInNestedArray($arr, 'e.f.g', null)); ?>
based on hJUJX
Output for 5.6.0 - 5.6.30, hhvm-3.15.4, 7.0.0 - 7.3.0beta1
Notice: Undefined index: a in /in/jk3XN on line 8 Notice: Undefined index: b in /in/jk3XN on line 8 Notice: Undefined index: c in /in/jk3XN on line 8 Notice: Undefined index: d in /in/jk3XN on line 8 1Array ( [a] => Array ( [b] => Array ( [c] => Array ( [d] => e ) ) ) ) 2Array ( [b] => Array ( [c] => Array ( [d] => e ) ) ) 34 Notice: Undefined index: e in /in/jk3XN on line 22 Notice: Undefined index: f in /in/jk3XN on line 22 Notice: Undefined index: g in /in/jk3XN on line 22