Using variables when declaring other variables
Moderator: General Moderators
Using variables when declaring other variables
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?
- MrPotatoes
- Forum Regular
- Posts: 617
- Joined: Wed May 24, 2006 6:42 am
- n00b Saibot
- DevNet Resident
- Posts: 1452
- Joined: Fri Dec 24, 2004 2:59 am
- Location: Lucknow, UP, India
- Contact:
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:Technically, it's possible, but I wouldn't do it. Instead, I'd use an Array object.
If you wanna know, there is alternate method to eval, a feature in PHP called `variable variables`.feyd wrote:If you insist on using variable generation, you'll need to use eval().
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
";
?>
- n00b Saibot
- DevNet Resident
- Posts: 1452
- Joined: Fri Dec 24, 2004 2:59 am
- Location: Lucknow, UP, India
- Contact: