I would like to dynamically set/get array's elements with a string as element keys.
So I'm looking for the good way to convert a string into a multiple keys array.
I reach the expected result with that piece of ugly code, which I'm not proud of:
function arrayElementSet($str, $value, array &$array)
{
$arrayStr = "['".preg_replace('/\./', "']['", $str)."']";
eval('$array'.$arrayStr.'="'.$value.'";');
}
function arrayElementGet($str, array &$array)
{
$arrayStr = "['".preg_replace('/\./', "']['", $str)."']";
eval('$ret=$array'.$arrayStr.';');
return $ret;
}
$array = array();
arrayElementSet('d0.d1.d2.d4', 'bar', $array);
$wantedElement = arrayElementGet('d0.d1.d2', $array);
print_r($array);
/*
wantedElement looks like:
Array
(
[d4] => bar
)
$array looks like:
Array
(
[d0] => Array
(
[d1] => Array
(
[d2] => Array
(
[d4] => bar
)
)
)
)
*/
But that's pretty ugly, plus I would like to avoid the eval() function.
I'm not particularly attached to an array solution, if there is a nice solution with an object or whatever, I'll take it.
EDIT:
Just to know. Two Helper Functions from Laravel comes out of the box (array_get and array_set):