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.
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);
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).
Yes, PHP supports arrays as session variables.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With