Page 1 of 1

dynamic variables

Posted: Sat Jun 18, 2005 4:13 am
by thegreatone2176
Ok i searched and searched and didnt find anything what i need to know is how to create dynamic variables...

I have an array and looped through it setting the name= part of the form , now what i want to be able to do is say

Code: Select all

foreach($arr as $val)
$newval = $_POST['$val'];
$val being the element of the array that is being posted

I am really stuck so any help would be greatly appreciated.

Posted: Sat Jun 18, 2005 5:42 am
by dnathe4th
I'm not really clear on what you're trying to do, but from the looks of it, you're only going to have one $newval value; whatever the last one was.

Posted: Sat Jun 18, 2005 8:19 am
by Chris Corbyn
Not sure exactly what you mean but this is how to do the array element thing you're getting at (lose the quotes so the variable is not parsed as a string):

Code: Select all

foreach($arr as $val) {
    $newval = $_POST[$val];
    //Do whatever with the new value
}

Posted: Sat Jun 18, 2005 8:19 am
by Bennettman
If I'm thinking about this right, you've got a form, with input names say: input1, input2 etc.
At the same time, you've got an array $arr, which iterates to: [0] => 'input1', [1] => 'input2', etc.

...and at each iteration of the foreach, you want to load the input value of everything in $arr, into $newval. I think.

The only problem you've got with that code is that single-quoted strings parse exactly as they appear (apart from escaping quotes). So, $_POST['$val'] is $_POST with key "$val", whereas you want the value of $val.

To fix it, either don't quote $val, or enclose it in double quotes: "$val". Both will parse it into its value.

Code: Select all

foreach($arr as $val)
$newval = $_POST[$val];

Posted: Sat Jun 18, 2005 11:04 am
by thegreatone2176
thanks guys that worked great

I thought I tryed without the quotes and it didnt work but it does now. I was really tired (note the time of my post :))

thanks again

Posted: Sat Jun 18, 2005 2:32 pm
by John Cartwright
In your instance, $newval will only contact the last $arr element, as each instance it will be overwritten.

Code: Select all

foreach($arr as $val) {
   $$newval = $_POST["$val"];
}
More Info @ http://ca.php.net/language.variables.variable

You could also use extract() for the same effect

Code: Select all

extract($_POST);
Although it could potentially be a security problem. I generally like to check what variable I receive versus what I am expecting, if it does not match, boom. End Script.

Posted: Sat Jun 18, 2005 8:43 pm
by thegreatone2176
well its hard to explain, but I made it so the checkboxes on the form were dynamic and like you say you only get the current value but I added the current value to a comma separated string that I store into a .txt.

thanks again for the help