Dynamicly create variables??

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
nirus
Forum Newbie
Posts: 16
Joined: Fri Dec 17, 2004 12:35 am
Location: Iowa

Dynamicly create variables??

Post by nirus »

Ok I want to dynamicly create variables for posted data. We do not know how many variables there are going to be... could be 10 or 62.

You can see what I am trying to do which obviously will not work ... $host$i embeded into a while statement while stepping $i by 1

Code: Select all

//here is the value we do not know... could be 2 or 63 we are just unsure
$hostlines= $_POSTї'hostlines']; 

$i = 1;
while ($i < $hostlines)&#123;
        $host$i = $_POST&#1111;'host$i']; 
         $i++;
                 &#125;
//this is what I want as a result
echo "$host1, $host2, $host3, $host4,";



Basically I am trying to automate this:
$host1 = $_POST['host1'];
$host2 = $_POST['host2'];
$host3 = $_POST['host3'];
$host4 = $_POST['host4'];


hostlines is comming from <input's> on a form. all the inputs have dynamicly created name="host1" or name="host8"

You deserve a gold star if you can make this happen! :D
- Nirus
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post by magicrobotmonkey »

Code: Select all

//here is the value we do not know... could be 2 or 63 we are just unsure
$hostlines= $_POST['hostlines'];

$i = 1;
while ($i < $hostlines){
         $name = "host".$i;
         $$name = $_POST[$name];
         $i++;
                 }
User avatar
protokol
Forum Contributor
Posts: 353
Joined: Fri Jun 21, 2002 7:00 pm
Location: Cleveland, OH
Contact:

Post by protokol »

This is what the extract() function is for.
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post by magicrobotmonkey »

gew I hate extract().
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

the smart-er extract I wrote and posted for several someones may work.. however.. if the fields were named "host[]" they'd come in as an array, so they would be simple to access, without any additional parsing..
Post Reply