What does the syntax '$ {$ key} = $ val' inside a loop in PHP mean?

It's time to stop searching just ask. I can not find the answer online for the life of me. Anyway, I am looking at another user's code, and I have this syntax inside the loop, and I don’t know exactly what is going on.

foreach($params as $key => $val) { ${$key} = $val } 

This is $ {$ key}, which I do not understand.

+4
source share
4 answers

It assigns all key-value pairs in the array to the actual variables.

${$key} is evaluated twice. It takes the value of $key for this value and evaluates it as a string. Therefore, if $key was the string 'foo', then the final operation would be $foo = $val .

+1
source

This is called variable variables . In your loop, the code sets a variable whose name $key matches the value of $val .

The loop can be replaced with extract() .

+4
source

This essentially does what extract() does:

 $params = array('a' => 'foo', 'b' => 'bar'); foreach($params as $key => $val) { ${$key} = $val } echo $a; // outputs 'foo' echo $b; // outputs 'bar' 
+3
source

This is called variable variables http://php.net/manual/en/language.variables.variable.php . If $key = 'test' , then ${$key} === $test. And so the result will be $test = $val .

+1
source

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


All Articles