简体   繁体   中英

How do I echo the session name in a foreach loop in PHP?

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 />';
}

This?

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

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 />';
}

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 />';
}

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM