I\'ve to implement a setter in PHP, that allows me to specify the key, or sub key, of an array (the target), passing the name as a dot-separated-keys value.
Yet another solution for getter
, using plain array_reduce
method
@AbraCadaver's solution is nice, but not complete:
'one.two'
from ['one' => 2]
My solution is:
function get ($array, $path, $separator = '.') {
if (is_string($path)) {
$path = explode($separator, $path);
}
return array_reduce(
$path,
function ($carry, $item) {
return $carry[$item] ?? null;
},
$array
);
}
it requires PHP 7 due to ??
operator, but this can be changed for older versions pretty easy ...