tags:

views:

53

answers:

2

Hello,

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
+6  A: 
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];
}
David Kuridža
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.
erenon
It's not a typo, take a look at http://www.php.net/manual/en/language.operators.comparison.php. Less readable? Well, that depends from coder to coder, personally I prefer it.
David Kuridža
@David: I can't see any !===
erenon
Whoa! Ooops, you're right, have to start reading what I write twice before posting it. Thanks!
David Kuridža
+2  A: 

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).

Kris