0

I am trying to define a set of variables by setting them from SESSION and POST variables of the same name. (I.e. I want to transfer $_SESSION['a'] to $a.

I am trying to use an array of variables names (a, b, c) to define such a set using a foreach loop, but am having when trying to define them I end up with syntax like $$variable within the loop, which does not work. I've tried single and double quotes around the $variable, but no joy

$data = array (
        'a',
        'b',
        'c',
              );

foreach($data as $variable)
 {
   if (isset($_POST['$variable'])) $_SESSION['$variable']=$_POST['$variable'];
   if (isset($_SESSION['$variable'])) {$$variable=$_SESSION['$variable'];} else {$$variable="";}
 }

Any help greatly appreciated.

I'm trying end up with many instances of something like:

 if (isset($_POST['$a'])) $_SESSION['$a']=$_POST['$a'];
 if (isset($_SESSION['$a'])) {$a=$_SESSION['$a'];} else {$a="";}
Gideon
  • 1,878
  • 4
  • 40
  • 71
  • Oh dang, I accidentally deleted the intro explanation, let me edit – Gideon Nov 08 '12 at 01:09
  • Variables are only interpolated in double quotes, not single quotes. And here was no need for either in the first place. – mario Nov 08 '12 at 01:12
  • possible duplicate of [Why is PHP not replacing the variable in string?](http://stackoverflow.com/questions/11317743/why-is-php-not-replacing-the-variable-in-string) – mario Nov 08 '12 at 01:13
  • possible duplicate of [Difference between single quote and double quote string in php](http://stackoverflow.com/questions/3446216/difference-between-single-quote-and-double-quote-string-in-php) – mario Nov 08 '12 at 01:14
  • Have you read this page? http://php.net/manual/en/language.variables.variable.php – Nic Wortel Nov 08 '12 at 01:14

1 Answers1

1

The single quotes prevent $variable from being evaluated, just take them out.

$data = array (
        'a',
        'b',
        'c',
              );

foreach($data as $variable)
 {
   if (isset($_POST[$variable])) $_SESSION[$variable]=$_POST[$variable];
   if (isset($_SESSION[$variable])) {$$variable=$_SESSION[$variable];} else {$$variable="";}
 }
trapper
  • 11,716
  • 7
  • 38
  • 82
  • Thanks very much, I knew it would be something simple I was ignoring, got distracted by presuming $$ would break it. – Gideon Nov 08 '12 at 01:17