1

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
alesdario
  • 1,873
  • 6
  • 25
  • 38

4 Answers4

11

It creates 4 empty arrays:

$a, $b, $c, $d // arrays now
Arthur Halma
  • 3,943
  • 3
  • 23
  • 44
  • Oh, thanks. Let me ask a question to you. Do you think this is a good practice ? It seems "dark programming" – alesdario Jul 27 '11 at 09:59
  • 3
    @alesdario: Meanwhile its treated as "bad practice", but in some (minor) cases it may make things easier, or such. In fact I didn't used it ever. – KingCrunch Jul 27 '11 at 10:05
2

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$); 


?>
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
0

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();
Rads
  • 185
  • 1
  • 2
  • 16
0

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

iskandarm
  • 119
  • 5