Fueling Your Coding Mojo

Buckle up, fellow PHP enthusiast! We're loading up the rocket fuel for your coding adventures...

Popular Searches:

PHP session variable name as string

Hey everyone,

I'm facing a bit of a hurdle with PHP session variables, and I was hoping someone here could help me out. I'm currently working on a project where I need to access a session variable, but the variable name is stored as a string.

For example, let's say I have a session variable called "username", but I want to access it using the variable name stored in another variable, let's say "$var". So essentially, I want to do something like $_SESSION["$var"], where $var contains the string "username".

I've been searching for a solution but haven't been able to find anything helpful so far. Is there a way to achieve this in PHP? Any suggestions or examples would be greatly appreciated.

Thanks in advance!

All Replies


Hey friend,

I understand your dilemma with PHP session variables and accessing them dynamically. I went through a similar challenge in the past, and I stumbled upon an alternative approach that might interest you.

Rather than using variable variables, you can leverage the PHP function `$_SESSION` to achieve what you're looking for. By using square bracket notation and providing the variable string as the index, you can access the session variable dynamically.

Here's an example: if your variable `$var` contains the string value "username", you can access the session variable by using `$_SESSION[$var]`. This will fetch the username value stored in the session variable.

Give this method a shot, and it should help you solve your predicament. If you have any further questions or need more guidance, feel free to ask. Good luck with your project!


Hey there,

I've encountered a similar situation before, and I found a solution that worked for me. In PHP, you can use variable variables to achieve this.

What you can do is prepend a dollar sign ($) to your string variable, which will make it interpret the value as a variable name. So in your case, you could use $_SESSION[$$var] to access the session variable dynamically, where $$var will be replaced with the value stored in $var.

For example, if $var contains the value "username", $_SESSION[$$var] will be equivalent to $_SESSION['username']. This way, you can access the session variable whose name is stored in a string.

I hope this helps! Give it a try and let me know if you have any further questions.

New to LearnPHP.org Community?

Join the community