Based on Ugo Méda's response :
This version
- allows you to use it solely as a getter (leave the source array untouched)
- fixes the fatal error issue if a non-array value is encountered (
Cannot create references to/from string offsets nor overloaded objects
)
no fatal error example
$a = ['foo'=>'not an array'];
arrayPath($a, ['foo','bar'], 'new value');
$a
is now
array(
'foo' => array(
'bar' => 'new value',
),
)
Use as a getter
$val = arrayPath($a, ['foo','bar']); // returns 'new value' / $a remains the same
Set value to null
$v = null; // assign null to variable in order to pass by reference
$prevVal = arrayPath($a, ['foo','bar'], $v);
$prevVal
is "new value"
$a
is now
array(
'foo' => array(
'bar' => null,
),
)
/**
* set/return a nested array value
*
* @param array $array the array to modify
* @param array $path the path to the value
* @param mixed $value (optional) value to set
*
* @return mixed previous value
*/
function arrayPath(&$array, $path = array(), &$value = null)
{
$args = func_get_args();
$ref = &$array;
foreach ($path as $key) {
if (!is_array($ref)) {
$ref = array();
}
$ref = &$ref[$key];
}
$prev = $ref;
if (array_key_exists(2, $args)) {
// value param was passed -> we're setting
$ref = $value; // set the value
}
return $prev;
}