Skip to content
Advertisement

Trying to figure out how to delete item from cart in PHP

I am trying to make an e-commerce website and I can’t quite figure out how to get the cart to function. I am able to add amounts to the cart before purchase but I want it to delete the item from the cart when the quantity is set to 0.

JavaScript

Here is the cart variable that creates a table of all the products added

JavaScript

This works when I delete things going from the last piece in the array, going to the first thing added in the array in that order, but when I try to delete the first element or anything out of order first, it gives me an error. “Warning: Undefined array key 0″. What am I doing wrong?

Advertisement

Answer

The undefined index come from the use of unset(). The indexes of the array will not be re-ordered after unset() call.

Exemple:

JavaScript

You could:

  • use array_values() to re-index arrays.

    JavaScript
  • or, check the presence of the data in the loop :

    JavaScript

Another way is to use a data structure for the order:

JavaScript

then, use a foreach() to list

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement