Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - how to push array in Session?

If I have the following,

$this->Session->write('ScoreCardCriteria', 'test');

And want to add another item to ScoreCardCriteria as an array of items, how would I do so?

With regular PHP, It would be something like

$_SESSION['ScoreCardCriteria'][] = 'test';

I came up with this:

    $new_array = array_merge((array)$this->Session->read('ScoreCardCriteria'), array('test'));
    $this->Session->write('ScoreCardCriteria', $new_array);

But I'd love it if there was a more "cake" way to do it.

like image 816
David Ryder Avatar asked Jun 15 '11 20:06

David Ryder


People also ask

How do you push a session array?

We can add elements to it by array_push() function. array_push($_SESSION[cart],$prod_id); We can remove items from the array by using array_diff() function. $_SESSION[cart]=array_diff($_SESSION[cart],$prod_id);

How to push data in an array in PHP?

The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

Can PHP session store array?

Yes, PHP supports arrays as session variables.


1 Answers

You could do this:

$this->Session->write('ScoreCardCriteria', array( 'test' ) );

And then:

$data = $this->Session->read('ScoreCardCriteria');
$data[] = 'test';
$this->Session->write('ScoreCardCriteria', $data);

However, to be quite honest, CakePHP uses the $_SESSION object internally and just overrides the default session handlers. The only thing ->write does is parse a dot notated set path (which would look like foo.bar.x) which you are not doing. And echo debug information if you are watching particular values. It shouldn't hurt if you modify $_SESSION directly.

like image 189
Andrew Curioso Avatar answered Sep 24 '22 15:09

Andrew Curioso