1

I know I can call a variable dynamically like this:

$var = 'name';
$name = 'hello';
echo(${$var});

But how can I address an array in the same way (but not just one property like $var[$i]):

$var = 'arrayname[\'Subsections\'][\'Party\'][\'Description\']';
var_dump(${$var});

Thank you in advance, regards, Stefan

1
  • using a foreach loop? Commented Nov 23, 2013 at 16:38

1 Answer 1

2

You shouldn't use variable variables anyway. Use arrays.

In this case, you could have a helper function:

function getArrayPath($arr,$path) {
    foreach($path as $item) {$arr = $arr[$item];}
    return $arr;
}

Then, you can access like this:

$var = ["Subsections","Party","Description"];
$data = getArrayPath($arrayname,$var);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you - that worked for me. I dislike the much overhead just because I want to call a variable dynamically but fine with it ofc. Just two side notes - it took me not much but still the [] array syntax is not supported in all php versions (I was just aware of that because i came across that somewhere earlier this week) so I had to use the old array() syntax. And I think you wanted to write $arr[$item] instead of $arr[$path].... just for reference. :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.