-2

I was wondering is it possible to have an associative array within a session array? If so, what would be the best way to do it and how can I loop through it? I have tried the following but it doesnt seem to work:

//The variables are post variables from a form
$_SESSION['users'][$id] = array('name'=>$name, 'status'=>$status, 'salary'=>"20000");

Here is how I am trying to loop through the session array:

foreach ($_SESSION['users'] as $id=>$value) {
echo $value;
}

Also, If I knew an id how can I get the name? Can I do $_SESSION['users']['1234']['name']?

7
  • 1
    Yes, it is possible as the value is serialized for storage. Post the rest of your code so we can see what is causing the problem. Commented Oct 14, 2013 at 19:22
  • this is answer for you stackoverflow.com/questions/2306159/array-as-session-variable/… Commented Oct 14, 2013 at 19:24
  • Try doing $_SESSION['users'] = array(); first... Commented Oct 14, 2013 at 19:26
  • Why are you storing session info for multiple users in the same session??? Commented Oct 14, 2013 at 19:28
  • Anything that can be serialized (run through serialize) can be put into $_SESSION. That means strings, arrays, numbers, stdClasses etc., but not most resources/file handles/sockets. Commented Oct 14, 2013 at 19:28

1 Answer 1

2

Yes you can have an associative array within a session array. You can also loop through it with a for or a foreach loop. e.g.:

$array = $_SESSION['users'][$id];

foreach($array as $key => $value) {
    var_dump($array[$key]); //Will dump info about a single element
}

However, it would be helpful to see your error message or additional details of what you are trying to do and what about it that isn't working.

EDIT

Based on your updated question, since you are accessing and array of arrays (theoretically) you would need to nest a foreach with another foreach to get at your values.

foreach($_SESSION['users'] as $arrays) {
    foreach($arrays as $arrKey => $arrVal) {
        var_dump($arrays[$arrKey]);
    }
}

Running that on your data would output (with my own fake data to fill variables):

string(7) "johndoe"
string(6) "active"
string(5) "20000"
Sign up to request clarification or add additional context in comments.

3 Comments

Also, If I knew an id how can I get the name? Can I do $_SESSION['users']['1234']['name']?
@Matt9Atkins Yes you can, so long as ['name'] is a valid key inside the ['1234'] array.
@Matt9Atkins I've updated my answer based on your updated question. Hopefully that helps you out some more.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.