ToyotaMR2
ToyotaMR2

Reputation: 141

Php add to array without overrides existing value?

I have a simple shopping cart array. I can add in the Id fine. However each time I go to submit the form it overrides the existing value? What is the best way to stop this from happening? Below is an example of when the form is submitted

session_start();
$id = filter_var($_POST['Phone-ID'], FILTER_SANITIZE_NUMBER_INT);
$Phone_Title = filter_var($_POST['Phone-title'], FILTER_SANITIZE_STRING);
$Phone_Price = filter_var($_POST['Phone-price'], FILTER_SANITIZE_STRING);
$Phone_Quantity = filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT);



$_SESSION['cart']['Id'] = array();


$_SESSION['cart']['Id'] = $id;
var_dump($_SESSION['cart']);

Upvotes: 1

Views: 33

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

remove this line $_SESSION['cart']['Id'] = array(); (As it's recreate the empty array again and again)

You need to assign values to the array with new-index every-time. So do like this:-

$_SESSION['cart']['Id'][] = $id;

Note:- with your code it always over-writes the 0th index id presented in $_SESSION['cart']['Id'] array

Upvotes: 3

Related Questions