1

I am developing a simple online shop cart page using php and xml I have a issue while appending data to array. The working is that when we click on add to cart the id should append to an array and store in session variable:

<?php session_start(); 
if(!isset($_POST['addtocart']))
{
    $_SESSION["array1"] =array();
    array_push($_SESSION["array1"],$_GET["pid"]);   
    print_r($_SESSION["array1"]);
}
?>

It is not appending id only showing the id of the product that I clicked

2
  • 3
    You're re-initialising $_SESSION["array1"] every time you run the code. Change that line to if (!isset($_SESSION["array1"])) $_SESSION["array1"] =array();) Commented Aug 19, 2019 at 7:18
  • Possible duplicate of How to add elements to an empty array in PHP? Commented Aug 19, 2019 at 7:43

3 Answers 3

2

try this one.

session_start(); 
if( !isset($_POST['addtocart']) )
{
 if( !isset($_SESSION['array1']) ) $_SESSION["array1"] =array();
 $_SESSION['array1'][] = $_GET['pid']; 
}
print_r($_SESSION["array1"]);
Sign up to request clarification or add additional context in comments.

Comments

0

This should work well

<?php session_start(); 
$data = array();
if(!isset($_POST['addtocart']))
{
array_push($data, $_GET["pid"], "test", "more data");   
print_r($data);
}
?>

Comments

0

You can short using array_push to session


$_SESSION['addtocart'][ ]=$_GET['pid'];

Comments

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.