views:

165

answers:

4

I am looping through my session variables. I have been able to echo the session values, but I would also like to echo the session name that corresponds with that value.

How do I echo out the session variable name each time it loops?

This is the code I currently have:

foreach($_SESSION as $value) {
    echo  'Current session variable is: ' . $value . '<br />';
}
+1  A: 

The foreach loop allows to specify a variable for a key. Simply use $var => $val where $val is the variable holding the index and $val is the variable holding the value.

foreach($_SESSION as $key => $value) {
    echo  'Session variable ' . $key . ' is: ' . $value . '<br />';
}
Andrew Moore
Thanks for the detailed explanation!
zeckdude
+4  A: 

This?

foreach($_SESSION as $key => $value) {
    echo  'Current session variable ' . $key . ' is: ' . $value . '<br />';
}
thephpdeveloper
That is exactly what I need! Thank you!
zeckdude
no problem at all. the other answers probably got more details and you might want to read them as well.
thephpdeveloper
A: 

Try this:

foreach($_SESSION as $k => $v) 
{
   echo 'Variable ' . $k . ' is ' . $v . '<br />' 
}
codaddict
+1  A: 

With a foreach loop, you can get both keys' names, and the corresponding values, using this syntax :

foreach ($your_array as $key => $value) {
    // Use $key for the name, and $value for the value
}

So, in your case :

foreach($_SESSION as $name => $value) {
    echo  'Current session variable is: ' . $value . ' ; the name is ' . $name . '<br />';
}
Pascal MARTIN
Thanks for the clarification!
zeckdude