Page 1 of 1

Dynamic Variable Creation

Posted: Wed Jan 07, 2004 11:42 pm
by Frederick
My brain has officially turned off after 19 hours of programming, here's my dilema:

In the PHP sessions I have a variable called "firstname1" saved,

Im using as loop as such:

Code: Select all

$numberofpeople = 2; (this is actually in the session header also)
$current = 0;
while ($current < $numberofpeople) &#123;
++$current;

echo "Person Number $current<P>
echo "$firstname&#1111;$current]";

";
&#125;


Now, I know this line wont work: echo "$firstname[$current]";


This above code will print:

"Person Number 1
1

Person Number 2
2"

As you can see it ignores "$firstname" because the variable alone does not exist, but "$firstname1" and "$firstname2" do.

How do I combine "firstname" and "$current "to give me a usable variable to pull in the info from the session?









Posted: Wed Jan 07, 2004 11:56 pm
by Gen-ik
I think something like the following should work.. I know the first example does anyway because I use it quite often.

Code: Select all

<?php

// Example One
$varName = "example";
$varValue = "the new variable 1";
${$varName} = $varVariable;
echo $example;

echo "<br />";

// Example Two
$varNameA = "another";
$varNameB = "Example";
$varValue = "the new variable 2";
${$varNameA.$varNameB} = $varValue;
echo $anotherExample;

echo "<br />";

// Example Three
$varName = "yetAnother";
$varValue = "the new variable 3";
${$varNameA."Example"} = $varValue;
echo $yetAnotherExample;

?>