You definately don’t need eval() or variable variables here. All you need to do is dynamically create strings, which doesn’t require eval();
php even supports a convenient way to receive variable names with array like notation via get post cookie, which it will parse into arrays for you. It even supports both numerical and string indexed arrays. http://www.php.net/manual/en/faq.html.php#faq.html.arrays
With and without that php feature, you’re still just making strings.
urlParams = [];
for (i=0; i<myList.length; i++) {
queryStringName = 'foo' + i;
urlParams.push(queryStringName + '=' + myList[i]);
}
alert(urlParams.join('&'));
// or php specific array feature
urlParams = [];
for (i=0; i<myList.length; i++) {
urlParams.push('foo[]=' + myList[i]);
}
alert(urlParams.join('&'));
In javascript and php at least, it’s extremely rare that variable variables are a better solution than arrays.
I’m new here, but will probably be racking up the post counts with my javascripting ignorance.
I’m having what seems to be a similar problem to this initial one and neither of the solutions (eval or arrays) seems to work for me.
In this code, using the eval example, I need to load dynamic variable values (some pseudo code in loop)
Any help greatly appreciated!
var myPanels=new Array("Email","News","Finance");
for (i=0;i<myPanels.length;i++) {
eval("div" + i + " = myPanels[i]");
//.. so that I end up with 'divEmail', 'divNews', 'divFinance'
eval("dynamic" + i) = new customobject.that.I'm.instantiating("blah","blah");
eval("dynamic" + i).render();
//..and in these two lines I'm creating a new object with each of the new variables, and doing something with them
}
var myPanels=new Array("Email","News","Finance");
// object, often used like associative array
var div = {};
// array
var dynamic = [];
for (i=0;i<myPanels.length;i++) {
div[myPanels[i]] = 'I am div.' + myPanels[i];
dynamic[i] = new customobject.that.Im.instantiating("blah","blah");
dynamic[i].render();
}
alert(div.Email)
alert(div['News'])
var key = 'Finance';
alert(div[key])
I challenge someone to post some realistic code that is better served(readability, speed, organization) by using eval() to create variable variables opposed to arrays or objects. There’s very few meaningful cases.