Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

It's time to stop searching a just ask. I can't find an answer online for the life of me. Anyway, I am going through someone else's code and they have this syntax inside of a loop and I'm not sure exactly what is happening.

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

It's the ${$key} that I don't understand.

like image 323
moult86 Avatar asked Jan 18 '23 07:01

moult86


2 Answers

This is called variable variables. In your loop, the code will set the variable who's name is $key to the value $val.

The loop could be replaced with extract().

like image 108
Tim Cooper Avatar answered Jan 20 '23 22:01

Tim Cooper


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'
like image 22
daiscog Avatar answered Jan 20 '23 20:01

daiscog