2

I have a PHP array, set up using

$this->cart = array();

Which is all ind and dandy except the array will not, no matter what i do, take new values, but only replaces the existing values with the new ones.

I've tried array_merge, array_push and others and the same thing happens but this is the code that should work.

$this->cart[]=$input;

The first time that is used, it say there's one item in the array "Array ( [0] => 1 " The second time it's used it will show this, replacing the first value "Array ( [0] => 2 ) "

Adding values are triggered by a form with pulling the ID and putting it into the array as the value

echo '<input type="hidden" name="addeditem" value="2">';

But no matter what code, it will not append the array, only replace it, any ideas. I have tried adding a key and value, as well as creating a second array and merging it in and nothing works.

The function to add to cart is this

function addToCart($input){
$this->cart[]=$input;
$this->setCartCount();
}

Solved: See comments.

alpha1
  • 157
  • 8
  • 3
    Your array is probably being reset somewhere else. – Sam Dufel May 21 '12 at 15:25
  • Check if you don't re-create the array before you add the new item. Try to dump its value just before adding new item. Does it really have one item already? – Jan Turoň May 21 '12 at 15:28
  • Got it! Sam Dufel nailed it, somewhere in my testing i removed the array from sessions and onto the page, which reset it everytime it started. Post it as an answer and i'll check it off for you. – alpha1 May 21 '12 at 15:30

2 Answers2

1

Are you sure that $this->cart is a global variable and that the array isn't created every time you call addToCart() ?

Try sth. like this:

  1. have a cart Object

    public class cart{
    
       private $items;
       function __construct() {
         $items=array();
       }
       public function addToCart($item){
         $this->items[]=$item;
       }
    }
    
  2. Add the Item to the cart somewhere else in your code.

    $cart=$manager->getCart();
    $cart->addToCart($your_new_item);
    
cb0
  • 8,415
  • 9
  • 52
  • 80
-1

The name should be following : addeditem[]

Bhavesh G
  • 3,000
  • 4
  • 39
  • 66
erdeszt
  • 799
  • 5
  • 12
  • Nah that's not it. $itemId = $_POST['addeditem']; and then runs this $ShoppingCart->addToCart($itemId); – alpha1 May 21 '12 at 15:24
  • This way $_POST['addeditem']; will be an array containing all of the hidden inputs' value – erdeszt May 21 '12 at 15:26