Variable 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
rhampton
Forum Newbie
Posts: 2
Joined: Sun Jan 23, 2011 3:58 pm

Variable Variables

Post 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!
Peec
Forum Commoner
Posts: 33
Joined: Fri Feb 22, 2008 3:58 am

Re: Variable Variables

Post 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);

?>
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Variable Variables

Post 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.
rhampton
Forum Newbie
Posts: 2
Joined: Sun Jan 23, 2011 3:58 pm

Re: Variable Variables

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