开发者

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 ec开发者_Python百科ho 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 />' 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜