PHP Setting a SESSION Variable Name Using A Variable

I would like to set the name of a $_SESSION variable to be the value of another variable. e.g.

$var = "123";
$_SESSION['$var'] = "yes";

echo $_SESSION['123'];  // Would like to echo "yes"
echo $_SESSION['$var'];  // Would also like to echo "yes"

I performed a vardump($_SESSION) and the session variable is literally set to "$_SESSION[$var]". How can I achieve the result I require?

Many Thanks.

Upvotes: 1

Views: 10896

Answers (1)

John Conde
John Conde

Reputation: 219924

Ditch the single quotes. They make PHP parse the $ as a literal dollar sign instead of the beginning of a variable name.

$_SESSION['$var'] = "yes";

should be:

$_SESSION[$var] = "yes";

Upvotes: 8

Related Questions