1

I have this code to add new elements to a multidimension array:

$this->shopcart[] = array(productID => $productID, items => $items);

So how do i remove an element from this array? I tried this code, but its not working:

public function RemoveItem($item)
{
    foreach($this->shopcart as $key)
    {
        if($key['productID'] == $item)
        {
            unset($this->shopcart[$key]);               
        }
    }
}

I get this error:

  • Warning: Illegal offset type in unset in C:\xampplite\htdocs\katrinelund\classes\TillRepository.php on line 50
3
  • The first code sample might misses some '-s around the keys. Commented Nov 10, 2009 at 17:06
  • @ricebowl: It must be the unset one. Commented Nov 10, 2009 at 17:07
  • @erenon, probably, yeah. But I just like to be sure =) Commented Nov 10, 2009 at 17:08

2 Answers 2

7
public function RemoveItem($item)
{
        foreach($this->shopcart as $i => $key)
        {
                if($key['productID'] == $item)
                {
                        unset($this->shopcart[$i]);   
                        break;                        
                }
        }
}

That should do the trick.

Update

There is also an alternative way:

if ( false !== $key = array_search($item, $this->shopcart) )
{
    unset($this->shopcart[$key];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Upvote for the first example. Typo in the second: !== insted of !===, and the second one is much less readable; don't use it if it's possible.
It's not a typo, take a look at php.net/manual/en/language.operators.comparison.php. Less readable? Well, that depends from coder to coder, personally I prefer it.
Whoa! Ooops, you're right, have to start reading what I write twice before posting it. Thanks!
2

You're not enumerating over indices, but values there, to unset an array index, you have to unset it by index, not by value.

Also, If your array index is actually the productID you can eliminate the loop altogether:

public function RemoveItem($productID)
{
    if (isset($this->shopcart[$productID]))
    {
        unset($this->shopcart[$productID]);
    }
}

Your example doesn't show how you are adding items to $this->shopcart, but this may or may not be an option for you depending on the needs of your project. (i.e. not if you need to have seperate instances of the same productid in the cart).

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.