0

In a php page I'm getting values and I can save it like follows:

<?php
 session_start();
// store session data
$_SESSION['advert']=8;
?>

and retrieve it like follows:

<?php
   //retrieve session data
   echo "advertID=". $_SESSION['advert'];
?>

and I can retrieve the value as 8 later.

But I need to save three product value IDs in a PHP array in a search session and later I need to retrieve them and connect them with the database(my SQL) to build up a compare table among those three products. How can I save three values in a PHP array and retrieve them later in a PHP session?

And if try to save more IDs:

  • 4th ID should be replaced with the first value in the array
  • 5th ID should be replaced with the second value in the array
  • 6th ID should be replaced with the third value in the array and goes like that..
4
  • Just... put them in an array and store that in the session...? What's the problem? Commented May 29, 2014 at 7:20
  • i haven't used php session and arrays for this kind of task earlier so i'm bit confused. Commented May 29, 2014 at 7:24
  • Then explain in more detail what exactly you're confused about. Commented May 29, 2014 at 7:25
  • if i need to add more values than three can we replace earlier values with new values Commented May 29, 2014 at 7:30

3 Answers 3

1
session_start();

if (!isset($_SESSION['products'])) {
    $_SESSION['products'] = array();
}

// add new product
$_SESSION['products'][] = $productId;

// trim array down to a maximum of three
$_SESSION['products'] = array_slice($_SESSION['products'], -3);

This way you keep a FIFO list of the last three products.

Sign up to request clarification or add additional context in comments.

Comments

1

Method 1: (just save values to session variables if you have small number of variables like 3.)

$_SESSION['var1'] = "value1";
$_SESSION['var2'] = "value2";
$_SESSION['var3'] = "value3";

Method 2: (using arrays)

$array = array();
$array['var1'] = "value1";
$array['var2'] = "value2";
$array['var3'] = "value3";

$_SESSION['array_values'] = $array;

when you want to replace:

  1. just repeat the method
  2. Or use $_SESSION['array_values']['var#'] = "value#";

Comments

0
$arrSession = array();
$arrSession[] = 'Value1';
$arrSession[] = 'Value2';
$arrSession[] = 'Value3';


$_SESSION['search'] = $arrSession;

//Retrive it as $_SESSION['search'] whereever necessary

1 Comment

if i need to replace the values in the array what can i do?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.