I'm working on a shopping cart, and i have one variable to set the items of the shopping cart, separated by commas then exploded into an array. I'm working on the remove an item part of it and i cant figure out fully functional way to do this. I'm using str_replace to remove it from that string of text, but where the problems come in depend on where its at in the variable.

What i have come up with so far, say the variable is "item1,item2,item3,item4" then if item 2 is removed it will become "item1,,item3,item4" and then replace ",," with ","

So what i need to figure out is if the first item or last item is removed, how do i get rid of a comma at the beginning or end, or if someone has a better method of doing this.

Thanks in advance.

    You could use [man]trim/man to handle the removal of the first or last elements.

    You could also consider going ahead with the explode(), and then using array_search() and unset the element.

      Well after messing with it for a while, here's what I have come up with:

      		$remove = $_GET['remove'];
      		$_SESSION['cart'] = str_replace($remove.",", "", $_SESSION['cart']);
      		$_SESSION['cart'] = str_replace(",".$remove, "", $_SESSION['cart']);
      		if ($_SESSION['cart']==$remove) {unset($_SESSION['cart']);}
      

      The first line removes it if its anywhere but the end, and the second line removes it if it is at the end, and then the third unsets the variable if its the only item left in the cart.

      Ive tested it and it seems to be working fine, I just wanted to check to see if anyone sees a problem with the way I'm doing it.

        if you kept then in an array until the end then imploded the array, it would easier to manipulate them individually (such as removing one)

          Write a Reply...