0

Can anyone help me to improve this code? I want to delete array if it already exists. Thanks

if(count($cart['Item']) > 0) {
    unset($cart['Item']);

    $items['Item'] = array();
    $cart = array_merge($cart, $items);
}
4
  • Have a look at codereview.stackexchange.com Commented Jul 12, 2011 at 6:17
  • Could you explain what exactly do you want to do here? Commented Jul 12, 2011 at 6:18
  • Do you want to delete the array if it exists or empty it if it has content? Commented Jul 12, 2011 at 6:19
  • @iAndr0idOs, want to delete array if exist $cart['Item'] Commented Jul 12, 2011 at 6:27

4 Answers 4

3

Apparently you want the $cart['Item'] variable to be an empty array after this step, no matter what it was before. So:

$cart['Item'] = array();

Done.

Sign up to request clarification or add additional context in comments.

Comments

0
if(!empty($cart['Item'])) {
    unset($cart['Item']);
}
  • !empty requires the array item to be both existent and not falsy (e.g. empty)
  • unset will delete the given key from $cart

However, if you want to replace it with a new, empty array:

$cart['Item'] = array();

No need to do anything else. PHP has a Garbage Collector.

Comments

0

If you just need to check if it exists. using isset() is faster in your case. Then you can just override it without any unsetting.

if( isset($cart['Item']))
{   
    $cart['Item'] = array();
}

Comments

0

you can try this,

if(isset($cart['Item']) && !empty($cart['Item'])) {
    unset($cart['Item']);

}else{
    $items['Item'] = array();
    $cart = array_merge($cart, $items);
 }

Thanks.

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.