I know how to set and get session value in magento 2. Here is what I do:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$mysession = $objectManager->create('Magento\Customer\Model\Session');

It works fine.

But I want multiple session value in an array; In simple PHP I've achieved this in following way:

**//Set session in  an array**
   foreach ($_productCollection as $_product):
   $_SESSION ['mytestvalues'] = array ();
   array_push($_SESSION['mytestvalues'], $_product->getEntityId());

/**/Get session array**
<?php print_r($_SESSION['mytestvalues']); ?>

Same thing I want to achieve in Magento 2. How to achieve this in magento 2?

1 Answer 1


Try this:

protected $mysession;

public function __construct(
    \Magento\Framework\Session\SessionManagerInterface $coreSession
    $this->mysession = $coreSession;
    $sessionValue = $this->mysession->getMyTestValue();
    $datas = array_push($sessionValue, $_product->getEntityId());
  • Error: Only variables should be passed by reference. Dec 5, 2017 at 6:55
  • I have updated my answer.
    – Nero Phung
    Dec 5, 2017 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.