How can I use $_SESSION? I want to use this code in Drupal 8.

if (isset($_SESSION['loop'])) {
     $loop = $_SESSION['loop'];
} else {
     $loop = 0;
}
for ($count = 0; $count &lt;= $loop; $count++) {
     $_SESSION['code'][$loop] = $code;
     $_SESSION['price'][$loop] = $price;
     $_SESSION['loop'] = $loop + 1;
}


This code worked correctly, but in Drupal 8 we should use this code.

// Setting a value.
$tempstore = Drupal::service('user.private_tempstore')-&gt;get('mymodule_name');
$tempstore-&gt;set('my_variable_name', $some_data);




// Getting a value.
$tempstore = Drupal::service('user.private_tempstore')-&gt;get('mymodule_name');
$some_data = $tempstore-&gt;get('my_variable_name');


I don't know how to change my code to use this service's API. How do I convert my code to use the user.private_tempstore service?
You listed all the elements you need. You just need to swap out the set and get you were originally using with the ones you provided.

This:

$loop = $_SESSION['loop'];


Will become this:

$loop = Drupal::service('user.private_tempstore')-&gt;get('mymodule_name')-&gt;get('loop');


And this:

$_SESSION['loop'] = $loop + 1;


Will become this:

\Drupal::service('user.private_tempstore')-&gt;get('mymodule_name')-&gt;set('loop', $loop + 1);


For your other elements, you can do the following.

This:

$_SESSION['code'][$loop] = $code;


Becomes this:

\Drupal::service('user.private_tempstore')-&gt;get('mymodule_name')-&gt;set('code', [$loop =&gt; $code]);


And this:

$_SESSION['price'][$loop] = $price;


Becomes this:

\Drupal::service('user.private_tempstore')-&gt;get('mymodule_name')-&gt;set('price', [$loop =&gt; $price]);