Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

proelitesunny's avatar

How to store associative array in session variable

I want to store an associative array in session variable. The structure should be like- 'arrayname' 9 => int 1 11 => int 2

Any help please??

0 likes
8 replies
GabrielBratescu's avatar

HI, Try this:

$array = ["9"=> 1, "11"=>2];

set it on session with: session($array);

AddWebContribution's avatar

Use below code to array in session variable.

Session::push('arrayName', [
   '9' => 1,
   '11' => 2
]);  

Hope, this work for you !

peacengara's avatar

Simple Solution that works always for me :

        $request->session()->push('session_detail', [
            'id' => 1,
            'name' => 'Catalyst'
        ]);

Getting the detail: request()->session()->get('session_detail')

COACHTHEM's avatar

@proelitesunny I am also facing the same.. I want to store details about the user as a single dimentional array in the sesssion.

I tried with @peacengara solution and when I try to access the session_detail using $request->session()->get('session_detail'); it return me below output

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Catalyst
        )

    [1] => Array
        (
            [id] => 1
            [name] => Catalyst
        )

    [2] => Array
        (
            [id] => 1
            [name] => Catalyst
        )

)

I am looking for output as below

Array
(
            [id] => 1
            [name] => Catalyst
)
RamjithAp's avatar

If you use 'push', when initially creating the array in the session, then the array will look like this only:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Catalyst
        )
)

Instead you should use 'put':

$request->session()->put('session_detail', ["id"=>1,"name"=>"Catalyst"]);

This will print

Array
(
            [id] => 1
            [name] => Catalyst
)
COACHTHEM's avatar

thanks @RamjithAp for the solution. Alternatively I found another way to implement this using global helper method session()

set the session like this

                session(['user' => [
                    'id'=> $id,
                    'name'=> 'Manny'
                ]]);

And access the details like this.

    $user_details = session('user');
    print_r($user_details);
1 like
Ahmad00100's avatar

please how can i get id alone , and name alone ??

Please or to participate in this conversation.