1
<?php 
session_start();
$pid = $_GET['pid']; 
$ptype = $_GET['ptype'];
$_SESSION = array();
$_SESSION['cart_items'] = array();

if (isset($_GET['add_cart']) && !empty($_GET['add_cart'])) {
  // Add new data to Session var

  $newdata = array($pid , $ptype, 1 );

  array_push($_SESSION['cart_items'], $newdata);
}

echo '<pre>';
var_dump($_SESSION);
echo '</pre>';

?>

array_push replaces the data already in the $_SESSION with $newdata variable in the $_SESSION instead of adding it.

For example:

I enter the url: ?pid=1&ptype=CH-&add_cart=Add+to+Cart And the array looks like this:

array(1) {
  ["cart_items"]=>
  array(1) {
    [0]=>
    array(3) {
      [0]=>
      string(1) "1"
      [1]=>
      string(3) "CH-"
      [2]=>
      int(1)
    }
  }
}

That's great. But when I enter another url like: ?pid=1&ptype=CPU-&add_cart=Add+to+Cart The array looks like this:

array(1) {
  ["cart_items"]=>
  array(1) {
    [0]=>
    array(3) {
      [0]=>
      string(1) "1"
      [1]=>
      string(4) "CPU-"
      [2]=>
      int(1)
    }
  }
}

instead of this:

array(1) {
  ["cart_items"]=>
  array(1) {
    [0]=>
    array(3) {
      [0]=>
      string(1) "1"
      [1]=>
      string(3) "CH-"
      [2]=>
      int(1)
    }
    [1]=>
    array(3) {
      [0]=>
      string(1) "1"
      [1]=>
      string(4) "CPU-"
      [2]=>
      int(1)
    }
  }
}

It replaces the data that was already in the Session. I want it to add to it. How do I do so?

Thanks in advance!

1
  • I don't think you need this: $_SESSION = array(); . Session is already an array even without you defining it explicitly. Commented Feb 18, 2016 at 15:08

1 Answer 1

3

change lines 5&6 from

$_SESSION = array();
$_SESSION['cart_items'] = array();

to

// $_SESSION = array();
// $_SESSION['cart_items'] = array();

array_push wasn't clearing your data. those two lines were clearing your session data on every page load.

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

3 Comments

Worked! Thanks! But could you explain why it didn't work with $_SESSION = array(); $_SESSION['cart_items'] = array();
because everytime those two lines ran, you completely REPLACED the session with empty arrays. "Hey, why is this empty box here? I just put the box here and now my stuff is gone"
Oh ok. Makes sense. Thanks again

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.