Page 1 of 1

dynamic variables generated from loop

Posted: Fri Sep 29, 2006 5:24 am
by markldxb
Refer to the snippet below:

$i=0;
for($i=0;$i<=$n;$i++){
$var.$i=$_POST["query".$i];
}

I just need to generate variables out of the loop. e.g. $var1,$var2,$var3...

I've tried the snippet using the format above but it never worked. Any solution for this?

Posted: Fri Sep 29, 2006 5:36 am
by miro_igov
Try this :

Code: Select all

$i=0;
for($i=0;$i<=$n;$i++){
 $temp = "var".$i;
 $$temp = $_POST["query".$i];
}
after this you will have n vars called $var0, $var1,...$var$n and their values will be $_POST['query1'], $_POST['query2'],...$_POST['query$n'].

Posted: Fri Sep 29, 2006 5:44 am
by Oren
Dude, I don't know what you are trying to do. I can give you few tips though:

1. Get a good PHP book and have a read.
2. Take a look at range().
3. Take a look at list() and extract().

:wink:

Posted: Fri Sep 29, 2006 5:54 am
by Mordred
4. Take a good look at arrays.

Posted: Fri Sep 29, 2006 5:59 am
by miro_igov
You guys are right, but he asks how to create variables with dynamic names, he does not look for any suggestions for better coding style.