Page 1 of 1

Dynamically create variables in loop

Posted: Mon Apr 17, 2006 9:13 pm
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...

Posted: Mon Apr 17, 2006 9:16 pm
by feyd

Posted: Tue Apr 18, 2006 3:09 am
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?
   */
}