How to create a dynamic variable using PHP?

I am trying to build a dynamic variable in PHP and, despite several questions on this issue, already here in StackOverflow, I'm still inactive ...: /

Variables are something that I never understood - I hope someone here can point me in the right direction. :)

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

Obviously this doesn't work, but if I hardcode the variable as such:

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

... then everything is in order, so obviously I'm not building my dynamic variable correctly. Any ideas?

UPDATE:

Hmm, ok I should have indicated that these are not keys in the array - I address nodes in XML using an identifier that is listed as an attribute for each node, so 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> 

Hope this helps explain the situation a bit. :)

+3
source share
5 answers

Why do you think you need dynamic variables? Doesn't that do what you want:

 $data['query']->section[$child['id']]->subsection[$grandchild['id']]->page[$greatgrandchild['id']] = "Fluffy Rabbit"; 
+6
source
 $foo = "hello"; $$foo = " world"; //echo $foo.$$foo; echo $foo.$hello; 
+1
source

In this example, you do not need dynamic variables.

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

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

Usually you use dynamic variables as follows:

 $variable = "variableName"; $$variable = "Some value"; echo $variableName; 

This will display:

 Some value 

EDIT

I completely agree with ircmaxell

+1
source

It looks like you are confusing variables with a good array . Variables are a mechanism that allows you to read (or write) a value to a variable whose name is unknown or may change, and, frankly, they are hardly ever needed:

 <?php $first_name = 'John'; $last_name = 'Smith'; $display = 'first_name'; echo $$display; // Prints 'John'; $display = 'last_name'; echo $$display; // Prints 'Smith'; 

However, your code assumes that you want to access the key inside the array:

 <?php $person = array( 'first_name' => 'John', 'last_name' => 'Smith', ); $display = 'first_name'; echo $person[$display]; // Prints 'John'; $display = 'last_name'; echo $person[$display]; // Prints 'Smith'; 

In PHP, an array key is an integer or a string, but it does not need to be literal: you can extract the key from a variable.

+1
source
 $foo='bobo'; echo $foo;//"bobo" $$foo='koko'; echo $$foo;//"koko" echo $bobo;//"koko" 
0
source

Source: https://habr.com/ru/post/1335062/


All Articles