Dynamic Variable Creation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Frederick
Forum Newbie
Posts: 13
Joined: Fri Nov 15, 2002 9:42 am

Dynamic Variable Creation

Post 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?








Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post 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;

?>
Post Reply