Search code examples
phparrayssessiontransfervar-dump

How to get all variables from an array and echo it as a $_SESSION?


Page 1: On the page 1 I have a for loop:, which contains something like this:

$_SESSION['img_name'] = $img_name[$i];

When I call var_dump

var_dump($_SESSION['img_name']);

I get that there are 2 strings:

string(6) "a2.JPG" string(6) "a3.JPG"

So I normally make the link to page 2 and instead of using $_SESSION I use just $_GET like this:

echo '<a href="page2.php?img='.urlencode($img_name[$i]).'">.'.htmlspecialchars($img_name[$i], ENT_QUOTES).'</a>'.'</br>';

But today I do not want to do that that way, I want to store $img_name[$i] in a $_SESSION and get those two variables from a $_SESSION on page 2.

Page 2:

echo $_SESSION['img_name'];

But the problem is that when I echo a $_SESSION on page 2, it contains only the last variable from an array, it doesn't echo all. How to get all variables being stored in an array?

On page 2 var_dump shows:

string(6) "a3.JPG"

String

string(6) "a2.JPG"

is missed. :(

QUESTION 2:

Could You tell me how can I fetch the data outside the loop? Something like: "echo $_SESSION['img_name'];" but outside the loop.


Solution

  • You are overwriting the values for session each time in forloop

    $_SESSION['img_name'] = $img_name[$i];
    

    So change it to

    $_SESSION['img_name'][] = $img_name[$i];
    

    And in first page i think var_dump() in present inside for loop. So its coming correctly.