View Full Version : Resolved Variable Value + Variable
bluewalrus
01-21-2010, 05:08 AM
How can I get the value of this variable to output the value of each variable? I think I might be doing this completely (I know the code is wrong but should i be using an array?). Thanks.
I have 8 values in my page that are like this and the $t's go till 8.
$t1 = "this";
$t2 = "that";
Incorrect code:
for ($i = 1; $i < $total +1; $i++) {
echo $t$total;
}
...you're trying to output the values of a bunch of variables?
something like this? unless there's a good reason *not* to, I'd put them in an array.
$tArray[1] = 'this';
$tArray[2] = 'that';
// etc.
foreach($tArray as $t){
echo $t.'<br>';
}
djr33
01-21-2010, 06:55 AM
Variable variables only are allowed for full variable names.
$$name is fine, but $xyz$abc is an error.
To compensate, you must use an intermediate string (annoying, but not hard):
$name = 'xyz'.$abc;
$$name; //now like "$xyz$abc";
So, for the above, you just need:
for($x=1;$x<9;$x++) {
$name = 't'.$x;
echo $$name;
}
djr33
01-21-2010, 07:30 PM
To add something to the post above, apparently there is another way around it:
http://www.php.net/manual/en/language.variables.variable.php
${'xyz'.$abc} should give the same results.
(Thanks to Nile for pointing that out-- http://dynamicdrive.com/forums/showthread.php?t=51714 )
bluewalrus
01-22-2010, 06:19 PM
I tried that like this
$contents{'p' . $i};
But it didn't work. I have it currently working with this
$steps = 'p' . $i;
and then to call it $$steps but I can only use this once, or is there another way to recall this?
djr33
01-22-2010, 06:26 PM
${'contentsp'.$}
$a$b is confusing, as is $a{$b}
PHP only accepts a single "argument" for the variable name, either $x or ${x}.
In the second version it can be complex because it's within brackets.
I'm not sure what you mean about "recalling" it. You can repeat the same code again,
$$steps. If the value of $steps has changed by then, then you can set it again.
Variable variables are confusing and frequently lead to problems. Almost always, arrays are a better way to go and with some good planning they are rarely needed. Occasionally, it is useful, but not that often.
One example is when you aren't sure about which variable to use and you can dynamically choose it:
$right = '5px'; $left = '10px'; $dir = 'left'; echo $$dir;
(You can imagine a script in which this might be useful, though more often than not there are still better ways to get around this.)
When it is as simple as incrementing by one, usually an array will be simpler overall.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.