fuzzy dunlop
fuzzy dunlop

Reputation: 477

php delete element from array

Im using cakephp 2.0 and i have data submitted that i want to cleanup, the array structure is below how do i delete the element (quoteitem) where the quantity=null?

i have this but it doesnt work;

foreach($this->request->data['Quoteitem'] as $qi) {
 if($qi['quantity']==null){
 echo 'quantity is null,delete this quote item from array';                 
 unset($qi);
}       
}

structure of array called ($this->request->data)

Array
(
    [Quote] => Array
        (
            [customer_id] => 72
            [user_id] => 104                
        )

    [Range] => Array
        (
            [id] => 
        )

    [Quoteitem] => Array
        (
            [0] => Array
                (
                    [product_id] => 
                    [unitcost] => 
                    [quantity] => 1
                )

            [1] => Array
                (
                    [product_id] => 
                    [unitcost] => 
                    [quantity] => 22
                )

            [2] => Array
                (
                    [product_id] => 339
                    [unitcost] => 5
                    [quantity] => 
                )     

        )

)

Upvotes: 1

Views: 5165

Answers (2)

Another Code
Another Code

Reputation: 3151

You can remove it using the array keys:

foreach($this->request->data['Quoteitem'] as $key => $qi) {
   if($qi['quantity'] == null){
      echo 'quantity is null,delete this quote item from array';                 
      unset($this->request->data['Quoteitem'][$key]);
   }       
}

Note that this will create gaps in the array (nonexistent indexes), usually this won't be a problem but if it is you can re-index the array with array_values().

Upvotes: 5

Nanne
Nanne

Reputation: 64409

Foreach makes a copy, try this:

foreach($this->request->data['Quoteitem'] as $key => $qi) {
   if($qi['quantity']==null){
      echo 'quantity is null,delete this quote item from array';                 
      unset($this->request->data['Quoteitem'][$key]);
   }       
}

Upvotes: 1

Related Questions