how to add an array to a session php

I want to add different stuffs to costumers cart but before adding the stuff transition in the database costumer must pay and then redirect to another page after Successful transition i need the chosen stuffs id's i tried using $_POST but the browser does not send the post value because of payment system in the middle i tried using sessions instead I want to add array of integers to a session control i already tried using this code

$t=array(1,2,3,4,5);
$_SESSION['exam_id']=$t

I don't know if i can do such a thing or not but what is the parallels

Upvotes: 0

Views: 594

Answers (5)

Manoj Sonagra
Manoj Sonagra

Reputation: 45

you can use array in session like this..

  1. you have to start session with session_start();
  2. and then store your array to session $_SESSION['items'][] = $item;

and then you use it, whenever you want:

foreach($_SESSION['items'][] as $item)
{
    echo $item;
}

Upvotes: 1

Rik_S
Rik_S

Reputation: 381

What you specified is working correctly. Sessions can hold arrays.

The session superglobal is an represented as an array itself within PHP, so you can just get and set values by doing the following

Setting:

$_SESSION['exam_id'][] = "new value";

or

$_SESSION['exam_id'] = array("new value", "another value");

Getting:

$_SESSION['exam_id'][0]; // returns a value

This returns the first value in the exam_id array within the session variable

Upvotes: 1

Ankur Bhadania
Ankur Bhadania

Reputation: 4148

$t=array(1,2,3,4,5);
$_SESSION['exam_id'] = array();
array_push($_SESSION['exam_id'],$t[0]);
array_push($_SESSION['exam_id'],$t[1]);
array_push($_SESSION['exam_id'],$t[2]);
array_push($_SESSION['exam_id'],$t[3]);
array_push($_SESSION['exam_id'],$t[4]);

Upvotes: 0

user4097807
user4097807

Reputation:

You can set PHP sessions equal to an array just like you're doing.

To set the $_SESSION variable equal to all POST data, you can do this:

$_SESSION['exam_id'] = $_POST;

Be sure to add session_start() prior to declaring any session variables.

Upvotes: 0

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

You will need to start the session. Make your code;

<?php
session_start();
$t = array(1,2,3,4,5);
$_SESSION['exam_id'] = $t;

Upvotes: 1

Related Questions