Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I build a dynamic variable with PHP?

I'm trying to build a dynamic variable in PHP and despite looking at a number of the questions on the matter already here on StackOverflow I'm still stumped... :/

Variable variables is something I've never quite understood - hopefully someone here can point me in the right direction. :)

$data['query']->section[${$child['id']}]->subsection[${$grandchild['id']}]->page[${$greatgrandchild['id']}] = "Fluffy Rabbit";

Onviously the above does not work but if I hard code a variable as such:

$data['query']->section[0]->subsection[3]->page[6] = "Very Fluffy Rabbit";

...then all is fine, so obviously I'm not building my dynamic variable correctly. Any ideas?

UPDATE:

Hmm, ok I should have pointed out that these are not keys in an array - I'm addressing nodes in the XML using an ID which is specified as an attribute for each node, so the XML has the following structure:

<subtitles>
<section id="0">
<subsection id="0">
<page id="1">My content that I want to write</page>
<page id="2">My content that I want to write</page>
<page id="3">My content that I want to write</page>
</subsection>
</section>
</subtitles>

Hopefully that helps explain things a little better. :)

like image 780
Nathan Pitman Avatar asked Jun 22 '26 04:06

Nathan Pitman


2 Answers

Why do you think you need dynamic variables here? Doesn't this just do what you want:

$data['query']->section[$child['id']]->subsection[$grandchild['id']]->page[$greatgrandchild['id']] = "Fluffy Rabbit";
like image 106
Erik Bakker Avatar answered Jun 24 '26 17:06

Erik Bakker


In this example you don't need dynamic variables.

If $child["id"] has the value 0, $grandchild["id"] has the values 3 and $greatgrandchild["id"] has the value 6, you should use something like:

$data['query']->section[$child['id']]->subsection[$grandchild['id']]->page[$greatgrandchild['id']] = "Fluffy Rabbit";

Normally you use dynamic variables like this:

$variable = "variableName";

$$variable = "Some value";

echo $variableName;

This will display:

Some value

EDIT

Totally agree with ircmaxell

like image 39
Rene Terstegen Avatar answered Jun 24 '26 16:06

Rene Terstegen