Search code examples
phpsession-variablesvariable-variables

Variable Variables with array element values syntax


I want to create a session variable but the session variable name I want to be dynamic. So what I need is the proper syntax for a variable name that is a $_SESSION variable.

I have tried the code below which creates a variable variable name and stored a value to it and it works just fine.

$xvalue = $_SESSION['delivery_id'];
$delivery_string = 'this_delivery_id_' . $xvalue ;
$$delivery_string = $_SESSION['delivery_id'];
echo "Variable name:&nbsp;" . $delivery_string . "<br/>";
echo "Session Variable Value:&nbsp;" . $this_delivery_id_29 . "<br/>";

The above code echos 29 for line 5; the desired result.

So working upon what worked with a variable variable I then just tried to make the variable name a $_SESSION variable name instead.

$value = $_SESSION['delivery_id'];
$xsession = "$_SESSION[\"" . $value . "\"]";  // this gives compilation error so dead stop. I also tried without the escapes and also a dead stop. I also tried escaping the [ and ] and got rid of the compilation error so the code runs but it does not give the desired result.
$$xsession = $_SESSION['delivery_id'];
echo "Variable name:&nbsp;" . $xsession . "<br/>";
echo "Session Variable Value:&nbsp;" . $_SESSION["delivery_id_29"] . "<br/>";

So line 2 of the code is where the problem is.


Solution

  • The issue comes from trying to interpolate the variable a little "too hard," if you escape $_SESSION[$value] you'll be left with the string "$_SESSION[$value]", which is not a valid name for a variable - you're attempting to access the variable as if it were defined like so: $$_SESSION[$value] = 'foo';. What you want to be doing is taking the value of that array element and using that in the variable variable, which needs to be done by referencing it.

    Either of the following seem to give the result you are going for; a straight variable variable:

    $value = 'foo';
    $_SESSION['foo'] = 'bar';
    $bar = 'baz';
    
    echo ${$_SESSION[$value]}; //prints baz
    

    One with another step, aiding in making it more clear:

    $identifier = $_SESSION[$value];
    echo $$identifier //prints baz
    

    I don't understand what you would be storing in this manner, but you may also investigate alternatives to achieve a cleaner, more straight-forward approach. If you clarify your use behind this, maybe someone will be able to suggest an alternative methodology.