Using variables when declaring other variables

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Using variables when declaring other variables

Post by GeXus »

Im using a loop and inside i am declaring a variable "var id" however I need to declare that variable based on an incremented id from the loop, such as "var id+x" is this posible?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Technically, it's possible, but I wouldn't do it. Instead, I'd use an Array object.

If you insist on using variable generation, you'll need to use eval().
User avatar
MrPotatoes
Forum Regular
Posts: 617
Joined: Wed May 24, 2006 6:42 am

Post by MrPotatoes »

feyd wrote:Technically, it's possible, but I wouldn't do it. Instead, I'd use an Array object
this is a much better idea
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Post by GeXus »

Gotcha! Thanks!
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post by n00b Saibot »

feyd wrote:Technically, it's possible, but I wouldn't do it. Instead, I'd use an Array object.
Agreed. Use of Array can save you writing much extra code and will help in reducing clutter from your code. Experienced programmers make perfect use of arrays.
feyd wrote:If you insist on using variable generation, you'll need to use eval().
If you wanna know, there is alternate method to eval, a feature in PHP called `variable variables`.

an example for you:

Code: Select all

<?php
$prefix = 'myVar'; //define prefix for our variable

foreach(range(1, 5) as $no)
 ${$prefix.$no} = $no;

print "
myVar1 = $myVar1
myVar1 = $myVar2
myVar1 = $myVar3
myVar1 = $myVar4
myVar1 = $myVar5
";
?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

n00b, he's talking Javascript. :P
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post by n00b Saibot »

must be after-effects of late-nite client fighting :oops:
Post Reply