i have an array with some info but i am trying to implement a way to access array dynamically with variable variables but i have no idea how, because php interprets that the whole string is a variable and not a variable with an associative key.
my example code:
$myArrayWithData = ["info" => 1];
$myvarvarArray = "myArrayWithData['info']";
print_r($$myvarvarArray);
expected behavior:
1
Actual Behavior:
`"Notice: Undefined variable: myArrayWithData['info']"`
i don want to hardcode indexes because i am trying to create a twig function that creates the array index path by a string and i am not able to predict the array Keys.
$myvarvarArray = "myArrayWithData"
print_r($$myvarvarArray["info"]); #hardcoded index
edit: my function can add more than 1 index
/**
* add a value to your twig array instead of using merge
*
* @param $object Array or object(public access) to set a new value
* @param string $context object complete path where value will be setted example "children.grandchildren.info"
* @param $value value to be inserted
*
*/
public function enhancedMerge($object, $contexts, $value){
$contexts = explode('.', $contexts);
$newObject = $object;
$path = '';
foreach($contexts as $key => $context){
$objectWithPath = 'newObject' . $path;
$contextIsArray = is_array(${$objectWithPath}) ? true : false;
if($contextIsArray){
$path .= "['" . $context . "']";
}else{
$path .= "->" . $context;
}
}
$objectWithPath = $newObject . $path;
$$objectWithPath = $value;
return $$newObject;
}