Jump to content
Larry Ullman's Book Forums

Variable Variables


Recommended Posts

I picked up Rasmus Lerdorf's "PHP Pocket Reference" and he talks about dynamic (variable) variables and I'm a bit confused.

 

$var = 'hello';
$$var = 'World';

 

I understand that the name of $$var will be set to the value of $var. Therefore $$var becomes $hello and has a value of 'World'.

 

However, later he talks about variable variables with arrays.

 

$array['abc'] = 'Hello';
$array['def'] = 'World';

 

He says you can turn these entity names into variables with the following code:

 

foreach $array as $index->$value{
$$index = $value;
}

 

That would make each array index a new variable named as the index. $abc = 'Hello' and $def = 'World'.

 

But why wouldn't it work without using variable variables? Is it because $index will keep getting overwritten with a new value?

 

foreach $array as $index->$value{
$index = value;
}

 

Thank you for any clarification you can give.

Link to comment
Share on other sites

Well with the example you've given at the bottom you're just creating (and then overwriting) a variable called 'index' rather than 'abc' and 'def'.

 

I'd also recommend getting into the habitat of using curly braces to define your variable variables because when you start working with arrays it can cause ambiguity.

 

foreach ($array as $index => $value){
   ${$index} = $value;
}

 

I appreciate that's just an example - but if you actually wanted to just do that then use the extract() function.

  • Upvote 1
Link to comment
Share on other sites

Well with the example you've given at the bottom you're just creating (and then overwriting) a variable called 'index' rather than 'abc' and 'def'.

 

I'd also recommend getting into the habitat of using curly braces to define your variable variables because when you start working with arrays it can cause ambiguity.

 

foreach ($array as $index => $value){
   ${index} = value;
}

 

I appreciate that's just an example - but if you actually wanted to just do that then use the extract() function.

 

Yes, the book mentions using the extract function. Can you demonstrate it so I can see what you're talking about? Thank you.

Link to comment
Share on other sites

Yeah sure - it's surprisingly simple but very powerful/useful:

 

$array['a'] = 'foo';
$array['b'] = 'bar';
$array['c'] = 'baz';
$array['d'] = array('hello', 'world');

extract($array);

 

Would be the same as writing:

 

$a = 'foo';
$b = 'bar';
$c = 'baz';
$d = array('hello', 'world');

 

It's really useful when you've extracted lots of fields from a database and want to put them into variables for use in templates etc...

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...