Forum Moderators: coopster

Message Too Old, No Replies

Simplify large numbers of variables posted in a form

I'm carrying large numbers of variables through different pages

         

s9901470

11:39 am on Oct 29, 2005 (gmt 0)

10+ Year Member



Hi

I'm carrying large numbers of variables through different pages and I wondered if there is a way to simplify this?

In the example below, I am collecting 100 variables from a form on the previous page but have to write them all out at the moment. Can PHP help me reduce this down?

$q1=$_POST['q1'];
$q2=$_POST['q2'];
$q3=$_POST['q3'];
$q4=$_POST['q4'];
$q5=$_POST['q5'];
...
$q100=$_POST['q100'];

Many thanks
Ed

grandpa

11:51 am on Oct 29, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Here's a snippet I use to echo post variables in a script.

while(list($key, $value) = each($HTTP_POST_VARS)) {
echo "<input type=\"hidden\" name=\"$key\" value=\"$value\">";
}

jatar_k

2:36 pm on Oct 29, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



$counter = 1;
while ($counter <= 100) {
${'q' . $counter}=$_POST[{'q' . $counter}];
}

that should workcan't remember if the braces are allowed inside the square brackets. If not just build it before, like so

$counter = 1;
while ($counter <= 100) {
$next = 'q' . $counter;
$$next=$_POST[$next];
}

grandpa

3:29 pm on Oct 29, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



$counter = 1;

I thought about a counter, almost wrote a sample. Then, I thought, the variable names ($q1 - $q100) should already be assigned as unique values from the form, and thus would appear in $key, ready to be used.

That, plus I couldn't remember either..

ergophobe

3:45 pm on Oct 29, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



PHP has a built-in utility for doing this.

Assuming there are no issues with namespace collisions (i.e. the indexes of the post variables don't conflict with other existing variables), the simplest way is just:

extract [php.net]($_POST);

If you want to make sure that you don't overwrite existing variables (say the $q series is okay, but there are other post vars that have index names that are the same as other variable names), then you can add some flags like so:

extract($_POST, EXTR_PREFIX_SAME, "post_");

If $_POST['q1'] = "I'm a post"; and $q1 = "I'm not a post"; then in the first case, after running extract(), $q1 will be "I'm a post", in the second example, $q1 will have it's original value and $post_q1 will be "I'm a post".