Manish Pradhan
Manish Pradhan

Reputation: 1188

Update a specific Session Variable

I am using this code to output all the registered session variables -

 echo "<pre>";
 print_r($_SESSION);
 echo "</pre>";
 exit();

This is what I get

Array
 (
[language] => english
[navigation] => navigationHistory Object
    (
        [path] => Array
            (
                [0] => Array
                    (
                        [get] => Array
                            (
                            )

                        [post] => Array
                            (
                            )

                    )

                [1] => Array
                    (

                        [get] => Array
                            (
                            )

                        [post] => Array
                            (

                                [number] => XXXXXXXXXXXX
                                [x] => 62

                            )
                )

            )

        )
 )

I would like to update the number variable in the [1] Array from XXXXXXXX... to 555555. I tried

$_SESSION['number'] = "55555555555555";

but that just ended up creating a new session variable called number outside the array with the 555.. value and not updating the right one. Can this be done?

Upvotes: 0

Views: 132

Answers (3)

Madbreaks
Madbreaks

Reputation: 19549

It's a nested array/object, so you have to traverse down to the array variable you want to set:

$_SESSION['navigation']->path[1]['post']['number'] = "55555555555555";

Upvotes: 2

Landon
Landon

Reputation: 4108

I often get confused on this myself and it takes me a bit to figure these really long guys out. A really easy way for you to figure this stuff out yourself is to do the following: At the end of your code, you have a print_r:

print_r($_SESSION);

Take a guess what the next level in the hierarchy is:

print_r($_SESSION['navigation'])

Run that, if you get an error, try something else. If it works, you should see a print of that guy and you're getting "closer" to your value. Once that looks good, tack on another attribute:

print_r($_SESSION['navigation']->path);

Does that work? Ok, continue. And do this all the way until you get exactly what you want.

Upvotes: 1

Landon
Landon

Reputation: 4108

Try this:

$_SESSION['navigation']->path[1]['post']['number']=123;

Upvotes: 1

Related Questions