Page 1 of 1

Is there a function to turn strings into a variable?

Posted: Tue May 20, 2008 3:35 am
by Sars
Hi,

Let me start off by saying that I'm quite new to this forum and uhh...hi.

Anywho, I'll also say that I design CMS's and such for a living - hence I'm not an idiot. This simply doesn't seem to be an easy question (though it should be...). Don't patronize me :D.

Question:

Is there a way to join two or more strings together to create an object/variable?

Eg.

Code: Select all

$apples_total=5;
 
$apples_1='I';
$apples_2='need';
$apples_3='to';
$apples_4='be';
$apples_5='displayed';
 
$apples_='apples_';
 
for ($i=1; $i<=$apples_total; $i++) {
  print ($apples.$i);
}
Now, as expected - that output 'apples_1'.

Unfortunaitly, as is evident above - I need to the above code to output 'I need to be displayed'.

In Actionscript 2.0, I can use

Code: Select all

apples_total=5;
 
apples_1='I';
apples_2='need';
apples_3='to';
apples_4='be';
apples_5='displayed';
 
apples_='apples_';
 
for (i=1; i<=apples_total; i++) {
  trace (eval(apples_+i));
}

Thanks in advance,
Jamen

PS. PLEASE don't ask why this needs to be done. The answer is basically a new content control test I'm working on for ameture coders.

Re: Is there a function to turn strings into a variable?

Posted: Tue May 20, 2008 3:40 am
by onion2k
References ...

Code: Select all

$var = "apples_";
$num = 1;
$apples_1 = "Hello";
 
echo ${$var.$num};
You can also concatenate the string first, eg

Code: Select all

$var = "apples_";
$num = 1;
$apples_1 = "Hello";
 
$con = $var.$num;
 
echo $$con;
Note there a 2 $ signs.

Re: Is there a function to turn strings into a variable?

Posted: Tue May 20, 2008 3:47 am
by Sars
Thanks alot! That was really frustrating me...