Everybody knows that you can access a variable in PHP using this: ${\'varName\'}. But when you need to get/set a variable witch is part of an array, why doesn\'t it work ? Suppo
You could do something like this, but it would be a really bad idea. Sorry Col. ;)
<?php
$mA = array();
$mVN = "mA['m1']['m2']['m3']";
eval('$'. $mVN . ' = "new value";');
print_r($mA);
?>
Shouldn't it work ?
No.
Everybody knows that you can access a variable in PHP using this: ${'varName'}.
Yes. Yet everybody knows that's lame.
How to refer dynamically to a php array variable(s)?
having array of ('my1','my11','my111')
you can refer to any particular array member using merely a loop.
I recommend you not to use dynamic variables like ${$var}
.
What you want is modifying a multi-dimensional associative array according to a path of keys.
<?php
$myArray = array(...); // multi-dimensional array
$myVarPath = array('my1', 'my11', 'my111');
setValueFromPath($myArray, $myVarPath);
function getValueFromPath($arr, $path)
{
// todo: add checks on $path
$dest = $arr;
$finalKey = array_pop($path);
foreach ($path as $key) {
$dest = $dest[$key];
}
return $dest[$finalKey];
}
function setValueFromPath(&$arr, $path, $value)
{
// we need references as we will modify the first parameter
$dest = &$arr;
$finalKey = array_pop($path);
foreach ($path as $key) {
$dest = &$dest[$key];
}
$dest[$finalKey] = $value;
}
This is a procedural example to keep it simple. You may want to put your hierarchical array and this functions inside a class.