alesdario
alesdario

Reputation: 1894

What does ${$item} mean?

I'm not able to understand braces goal in the situation below and I find no serious documentation about braces usage.

See the example below:

 $var = array('a','b','c','d');

 foreach($var as $item){

       ${$item} = array();

 }

I'm non understanding ${$item} meaning.

I've tried with var_dump before and after foreach loop but it seems nothing happens.

Any ideas?

Upvotes: 1

Views: 261

Answers (4)

Rads
Rads

Reputation: 195

Anything you put in curly brace will substitute value of the variable.

So the end value will be 4 empty arrays

${item} will become $a, ie: $a = array();
${item} will become $b, ie: $b = array();
${item} will become $c, ie: $c = array();
${item} will become $d, ie: $d = array();

Upvotes: 0

iskandarm
iskandarm

Reputation: 109

yes exactly it creates 4 empty arrays , you are creating variables on runtime , thats the usage of braces . here is examples of the usage of braces : braces in php

Upvotes: 0

DhruvPathak
DhruvPathak

Reputation: 43235

Curly braces create a variable with same name as string provided inside the curly braces. In your code, it creates 4 new variables $a,$b,$c,$d by taking strings from the array $var .

Here is an example to see the difference in variables created in your code: http://codepad.org/E2619ufe

<?php

$var = array('a','b','c','d');
$currentState = get_defined_vars();

foreach($var as $item){

       ${$item} = array();

 }

$newState =  get_defined_vars();
$newVariables = array_diff(array_keys($newState),array_keys($currentState));
var_dump($newVariables);

?>

Here is an example usage of curly braces: http://codepad.org/KeE75iNP

<?php

${'myVar'} = 12345;
var_dump($myVar);

/* also helpful when the variable name contains $ due to some reason */

${'theCurrency$'} = 4000;
var_dump(${'theCurrency$'});

/* uncomment line below, it will raise syntax error */
//var_dump($theCurrency$); 


?>

Upvotes: 2

Arthur Halma
Arthur Halma

Reputation: 4001

It creates 4 empty arrays:

$a, $b, $c, $d // arrays now

Upvotes: 11

Related Questions