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="";}
5

1 Answer 1

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="";}
 }
1
  • Thanks very much, I knew it would be something simple I was ignoring, got distracted by presuming $$ would break it. Commented Nov 8, 2012 at 1:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.