PDA

View Full Version : do-while and variables


Jabbamonkey
08-18-2002, 06:08 AM
I have a problem with a simple script (or so it seems). Here is the code....


$cat0 = "abc"; $cat1 = "def"; $cat2= "ghi"; $cat3 = "jkl";

$b = 0;
$c = 3;

do {
$test = $cat.$d; // <-- ERROR IS HERE
echo $test."<br>";
} while ($b <= $c);


What I'm trying to get as a result is:

abc
def
ghi
jkl

I want $test to equal the variable $cat# (not the value of cat#). I want to print the values of $cat0, $cat1, $cat2, $cat3 ... but I don't know how to "add" letters/numbers onto the name of an already existing variable. I hope I'm making myself clear....

Any help is appreciated.

Jabbamonkey

mordred
08-18-2002, 06:28 AM
What you are looking for are so called variable variables. They have unusual syntax, but can be quite handy in some cases. See this example, I changed it to to a for-loop since I find those easier to control.


$cat0 = "abc"; $cat1 = "def"; $cat2= "ghi"; $cat3 = "jkl";

$b = 0;
$c = 3;

for ($i = 0; $i <= 3; $i++) {
echo ${"cat$i"} . "<br>";
}


http://se.php.net/manual/en/language.variables.variable.php

Jabbamonkey
08-18-2002, 02:47 PM
Thanks alot Mordred. It worked great.

Ökii
08-18-2002, 08:12 PM
You could also eval() the variable variable statement, which would yield the same result.

eval("\$test = \$cat".$d.";");