Reputation: 1961
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);
}
Upvotes: 0
Views: 113
Reputation: 522597
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.
Upvotes: 3
Reputation: 3828
you can try this,
if(isset($cart['Item']) && !empty($cart['Item'])) {
unset($cart['Item']);
}else{
$items['Item'] = array();
$cart = array_merge($cart, $items);
}
Thanks.
Upvotes: 0
Reputation: 2119
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();
}
Upvotes: 0
Reputation: 318748
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.
Upvotes: 0