Dynamically create variables in loop

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
mparker1113
Forum Commoner
Posts: 28
Joined: Wed Apr 05, 2006 9:39 am

Dynamically create variables in loop

Post by mparker1113 »

Hi,

I have a for loop that I am in, and would like to store a piece of information. I would like to name this variable of information dynamically.

That is: for ($i = 0; $i < topNum; $i++){
$variable$i = topNum.field;
}

how can I do this, leaving me with $variable0, $variable1, etc ?

I am sure that there is a way -- I just am not getting the syntax right...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

As a general rule if you end up with variable names like:
$variable0;
$variable1;
YOU
SHOULD
BE
USING
AN
ARRAY!

because that's what it is and that will allow you to perform operations on them much more easily. You've already seen how unneccessarily difficult variables like this are to create (and PHP makes that stuff easier than all other languauges I know)
Try this:

Code: Select all

$var = array(); // create an array
for ($i=0; $i<$topNum; $i++){
   $var[] = topNum.field;  // add stuff into the array
   /* line above - do you mean:
   $topNum . $field 
   or
   $topNum->field?
   */
}
Post Reply