0

here i am trying to remove value from array, here i am passing action and id to page. i am checking if the values has been set and then perform action.

i want to remove value from array by value. here product_id is the value i am passing and the value has to be removed from array.

for ex:action=remove&product_id=22 the value 22 has to be removed from array

<?php
    if(isset($_GET['action']) && isset($_GET['product_id'])){
        if($_GET['action'] == "add"){
            $product_id = $_GET['product_id'];            
            $_SESSION['cart'][] =$product_id;
        }

        if($_GET['action'] == "remove"){
            unset($_SESSION['cart'][$product_id]);
            echo "product_remove";
        }
    }    
?>

how can i do this?

1
  • 1
    Use array_search() Commented Oct 6, 2015 at 11:42

4 Answers 4

3
if ($_GET['action'] == 'remove') {
    if (array_key_exists($product_id, $_SESSION['cart'])) {
        unset($_SESSION['cart'][$product_id]);
        echo 'product_remove';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

AS @Rizier said in the comment, use array_search, like below:

if($_GET['action'] == "remove"){
   $key = array_search ( $product_id, $_SESSION['cart'] );
   unset($_SESSION['cart'][$key]);
   echo "product_remove";
 }

Comments

1

You could use array_search($product_id, $_SESSION['cart']);

This will get you the key to unset. If you want to unset it the way you do now, you'll have to use the product id as an key when you add to the cart.

Hope this helps!

Comments

1

you could use array_search() as Rizier123 said, but a more performant way would be using array_flip and deleting by product_id

if($_GET['action'] == "remove"){
   unset(array_flip($_SESSION['cart'])[$product_id]);
   echo "product_remove";
 }

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.