dynamic variables generated from 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
markldxb
Forum Newbie
Posts: 2
Joined: Fri Sep 29, 2006 5:21 am

dynamic variables generated from loop

Post 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?
miro_igov
Forum Contributor
Posts: 485
Joined: Fri Mar 31, 2006 5:06 am
Location: Bulgaria

Post 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'].
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post 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:
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Post by Mordred »

4. Take a good look at arrays.
miro_igov
Forum Contributor
Posts: 485
Joined: Fri Mar 31, 2006 5:06 am
Location: Bulgaria

Post 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.
Post Reply