Jump to content

appended variable names


cfgcjm

Recommended Posts

I have a dynamic form which you can view at http://digiconmediagroup.com/Homeplate/portal/form.php

Each of the fields is automatically named Time1 Food1 Time2 Food2 etc dependent on the number of times the user enters.

I'm eventually having this form emailed through php but I'm having trouble figuring out how to assign the variables. I know this doesn't work but it's the concept that i want to use. If anyone has and ideas on how to make something like this run in php it would be of great help...

<?php
$recur = $_POST['numberOfRows'];

for($i=0; $i<$recur; $i++)
{
$time$i = $_POST['Time$i'];
$food$i=$_POST['Food$i'];
$amt$i=$_POST['Amt$i'];
$scale$i=$_POST['Scale$i'];
$emotion$i=$_POST['Emotion$i'];
}
?>

Link to comment
https://forums.phpfreaks.com/topic/87615-appended-variable-names/
Share on other sites

You could just make them arrays?  Just put [ ] around the $i in your code that you have, example:

 

<?php
$recur = $_POST['numberOfRows'];

for($i=0; $i<$recur; $i++)
{
$time[$i] = $_POST['Time'.$i];
$food[$i]=$_POST['Food'.$i];
$amt[$i]=$_POST['Amt'.$i];
$scale[$i]=$_POST['Scale'.$i];
$emotion[$i]=$_POST['Emotion'.$i];
}
?>

 

I haven't really tried putting a variable like $i in to a $_POST before but I don't see why it won't work :)  Then you can access the different $time, $food etc like $time[0] (would return the first value of the array) etc.

It is possible with eval(), but it's so much easier using arrays really.

 

<?php

$recur = $_POST['numberOfRows'];

for($i=0; $i<$recur; $i++) {

eval("\$time".$i." = \$_POST['Time".$i."'];");
eval("\$food".$i." = \$_POST['Food".$i."'];");
eval("\$amt".$i." = \$_POST['Amt".$i."'];");
eval("\$scale".$i." = \$_POST['Scale".$i."'];");
eval("\$emotion".$i." = \$_POST['Emotion".$i."'];");

}

?>

 

I believe that would be the code for creating it via eval, and each time you'd want to access it by a loop you'd have to use eval again etc.  It's just much simpler using arrays.

you can do it with "variable variables"

<?php
$times = array (1 => 12, 13, 14);

for ($i = 1; $i <= 3; $i++)
{
    ${'time'.$i} = $times[$i];
}

echo $time1 . '<br>';          // 12
echo $time2 . '<br>';          // 13
echo $time3 . '<br>';          // 14

?>

 

but arrays are easier to process

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.