views:

266

answers:

3

ok...in php how do i do this? given the following scenario:

// array of letters
var $letters = array('a', 'b', 'c');
// loop through array and create empty arrays with names like $a, $b, $c
foreach($letters as $letter) {
    var $$letter = array();
}
+1  A: 

Check out the eval() function: Eval

Jim H.
I would recommend against using eval. There is no situation in which eval() is the only solution, or even the best solution, and suggesting its use here is ill-advised and in my opinion, strange.
thomasrutter
+3  A: 

Your code was almost correct. You just need to remove 'var' on the 2nd and fifth lines.

// array of letters
$letters = array('a', 'b', 'c');
// loop through array and create empty arrays with names like $a, $b, $c
foreach($letters as $letter) {
    $$letter = array();
}

This works correctly (as you described). I tested it.

More information on variable variables here.

As an aside, I would recommend against using eval() in your PHP.

thomasrutter
so it does. i had a silly syntactical issue i didn't see.....thanks
ocergynohtna
You may want to look into turning on display_errors in your php.ini (on your development machine) - needs to be done that way to display parse errors. Also, the PHP command line interface can syntax check (ie calls it lint) - I have that integrated into my text editor/IDE.
thomasrutter
+2  A: 

You probably don't want to do this. Wanting to use variable variables is usually a sign of a failure to understand data structures and/or excessive cleverness. If you really want to do this, you could say something like...

extract(array_fill_keys($letters, array()));

...but it would be best if you didn't. Using nested arrays is probably a much better idea - especially since you can just say $nested['a'][] = 5 and PHP will append the value to the array, creating one if nothing is there. Alternately, you could just say $varname['key'] = 123 and, again, PHP will auto-create the array for you.

Sean McSomething
variable variables are actually very useful and powerful, and I've certainly wanted them over arrays multiple times. Example: using the array of columns that comes back SQL to populate a Model instance.
seanmonstar
seanmonstar - you mean like extract() http://us.php.net/manual/en/function.extract.php ?
Sean McSomething
no, i dont mean like extract. extract just fills the current scope with variables. variable variables allows me to assign the values from an array as properties of a model instance.
seanmonstar