Gideon
Gideon

Reputation: 1886

PHP syntax that will set a variable within a foreach loop using an array of variable names

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

Upvotes: 0

Views: 581

Answers (1)

trapper
trapper

Reputation: 11993

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

Upvotes: 1

Related Questions