Laravel - Session and Array

Asked

Viewed 2,143 times

3

I need to create an array:

array(
   0 => 0,
   1 => 0,
   2 => 1,
   3 => 0,
   4 => 0,
   5 => 1,
   6 => 0)

within a Session:

session('session_array')

and then individually add and redeem the values according to each key in the array. How do I do this? I could not understand very well seeing the documentation of the Laravel.

2 answers

3


If you are using Laravel 4

The session is created as follows:

Session::put('key',['um','dois']);

to display the data Session::get('key.um')

To the Laravel 5

to create

session()->put('key','value');

to display

session()->get('key');

1

If you want to add these array to a session value where you had already entered a given one, the best way would be to use the method push

session()->put('session_array', 1);

session->push('session_array', 2);

session->push('session_array', 2);

var_dump(session('session_array')); // [1, 2, 3]

You can also set the array directly on key specific:

session()->put('session_array', $array)

You can also access define values through point notation:

 session('session_array.nome', 'Wallace');
 session('session_array.1', 10);
 session('session_array.2', 20);

Alternatively you can also define a array directly:

session(['session_array' => [1, 2, 3, 4, 5]);

To get the values, you can do the following ways:

  //equivale a $_SESSION['session_array']['name']

 session('session_array.name'); 

 session('session_array.1');
  • session('session_array.name') is returning the whole array.

  • In that case, you must have defined the array in it all.

  • He is returning: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 1 [4] => 1 [5] => 1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.