Page 1 of 1

Using variables when declaring other variables

Posted: Sat Sep 30, 2006 9:00 am
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?

Posted: Sat Sep 30, 2006 9:25 am
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().

Posted: Sat Sep 30, 2006 9:38 am
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

Posted: Sat Sep 30, 2006 9:53 am
by GeXus
Gotcha! Thanks!

Posted: Sat Sep 30, 2006 12:19 pm
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
";
?>

Posted: Sat Sep 30, 2006 12:37 pm
by feyd
n00b, he's talking Javascript. :P

Posted: Sat Sep 30, 2006 12:39 pm
by n00b Saibot
must be after-effects of late-nite client fighting :oops: