Page 1 of 1

Variable Variables

Posted: Sun Jan 23, 2011 5:08 pm
by rhampton
Hopefully someone can throw a rookie a bone. I'm writing a multi-page registration form. The form on page 1 passes a list of names of attendees of a conference. Below is a very simplified section of page 2. The names are posting correctly to a database so I know they're getting passed but I can't get them to echo on the second page.

Code: Select all

<?php
$numattendees = 4;
$name1 = "Robert";
$name2 = "John";
$name3 = "Bill";
$name4 = "Fred";

$y = 1;
$namestr = "$name";
    
do {

    $names = $namestr.$y;

    echo "$names<br />";
    
    $y++;
} while ($y <= $numattendees);

?>
I get:

Code: Select all

1 
2 
3 
4 
[ /code]

And should be getting:
[code ]
Robert
John 
Bill 
Fred
[ /code ]

I've tried several variations but nothing.  Any help?

BTW, I tried the [code] tag for my results but it didn't render correctly.

Thanks!

Re: Variable Variables

Posted: Sun Jan 23, 2011 6:23 pm
by Peec
You should be using an array in this case.

See here :)

Code: Select all

<?php
$attendees = array('Robert', 'John', 'Bill', 'Fred');
foreach($attendees as $attendee){
   echo $attendee, '<br />';
}

echo "Total attendees: ", count($attendees);

?>

You can also do it like you want, like this:

Code: Select all

<?php
$numattendees = 4;
$name1 = "Robert";
$name2 = "John";
$name3 = "Bill";
$name4 = "Fred";

$y = 1;


do {

    eval('$names = $name'.$y.';');

    echo "$names<br />";

    $y++;
} while ($y <= $numattendees);

?>

Re: Variable Variables

Posted: Sun Jan 23, 2011 6:25 pm
by requinix
The corresponding HTML would be

Code: Select all

<input type="text" name="name[]" value="Robert" />
<input type="text" name="name[]" value="John" />
<input type="text" name="name[]" value="Bill" />
<input type="text" name="name[]" value="Fred" />
Peec: I was agreeing with you... up until when you added the code with eval(). Arrays are much better.

Re: Variable Variables

Posted: Sat Jan 29, 2011 4:22 pm
by rhampton
Thanks. "eval" worked but I have decided I need to learn arrays. Page one asks for $numattendees. Page two then loops to generate inputs for

$att1name
$att1age

$att2name
$att2age

etc.

Page three will write that to a MySQL table. I may be back with additional questions.