Forum Moderators: coopster

Message Too Old, No Replies

Variable Variables

Help with creating, displaying variable variables with a while loop

         

JoJoJohnson

11:02 pm on Mar 29, 2004 (gmt 0)

10+ Year Member



I am currently working on a project where on a basic html page a user will input a value for a certain number of items using input textboxes.

then when they click on calculate it takes them through to the php page where it will calculate which items had a value greater than 0 from the previous page and then perform various calculations with them (i can figure those out myself)

i have been able to do this with 16 if statements for each item, but could cut it down dramatically with variable variables. i want to do something similar to the code below, but am having trouble getting it working. can anyone help please?

just incase u needed to know, each textbox from the html page is named "TEXTBOX1", "TEXTBOX2", "TEXTBOX3", e.t.c up to "TEXTBOX16"

<?php

$count=1;
While($count<17){

$TEXTBOX = "$TEXTBOX".$count;
if($$TEXTBOX>0){

//VARIOUS DISPLAY CODE, NOT IMPORTANT FOR NOW

}
$count++;
}

?>

coopster

1:04 pm on Mar 30, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, JoJoJohnson!

There is another way to do this...

foreach (array_keys($_POST) as $key) { 
$$key = $_POST[$key];
print "$key is ${$key}<br />";
// print "$key is: " . $$key . '<br />'; // This format works, too!
}

Check out the PHP manual pages on variable variables [php.net], or search here on WebmasterWorld for related discussion on Accessing the $_POST array [webmasterworld.com].

JoJoJohnson

8:34 pm on Mar 30, 2004 (gmt 0)

10+ Year Member



wow that is great!

thank you for that, i really appreciate your time.

is there any chance you could explain to me exaclty how it works? i think the only bit i odnt really understand is this part "array_keys($_POST)"

also, with the original method i was using.....

<?php

$count=1;
While($count<17){

$TEXTBOX = "$TEXTBOX".$count;
if($$TEXTBOX>0){

//VARIOUS DISPLAY CODE, NOT IMPORTANT FOR NOW

}
$count++;
}

?>

...why was this not working? and would anyone be able to show me how to get it working? as i'd like to know more than one way of doing this if possible.

Thanks again