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

mshomali
  • 672
  • 6
  • 23
  • 3
    You're re-initialising `$_SESSION["array1"]` every time you run the code. Change that line to `if (!isset($_SESSION["array1"])) $_SESSION["array1"] =array();`) – Nick Aug 19 '19 at 07:18
  • Possible duplicate of [How to add elements to an empty array in PHP?](https://stackoverflow.com/questions/676677/how-to-add-elements-to-an-empty-array-in-php) – Lukas Aug 19 '19 at 07:43

3 Answers3

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"]);
V. Prince
  • 130
  • 9
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);
}
?>
Ivan
  • 389
  • 3
  • 13
0

You can short using array_push to session


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

dılo sürücü
  • 1,989
  • 1
  • 12
  • 19