Jump to content

If qty is 0 then remove index from array


arunpatal
Go to solution Solved by arunpatal,

Recommended Posts

Hi,

 

Here am i again with new problem....

//remove one quantity from item
if (isset ($_GET["remove"])) {
	$x = $_GET["remove"];

	foreach($_SESSION["viks_cart_array"] as $index => $value) {
		if ($_SESSION["viks_cart_array"][$index]['item_id'] == $x) {
			
			$q = $_SESSION["viks_cart_array"][$index]['quantity'];
			
			$_SESSION["viks_cart_array"][$index]['quantity'] = $q - 1;
			header("location:" . $_SERVER["PHP_SELF"]);
			break;
		
		}
	}
};

I want to remove index when quantity is zero

$_GET["remove"] values gets a item_id

Link to comment
Share on other sites

Well, I'm confused as to what you want since your code doesn't seem to have anything to do with the request. It would be helpful if you stated what is contained in the various variable. The array value $_SESSION["viks_cart_array"][$index] appears to be a sub-array with at least indexes of 'item_id' and 'quantity'. That a poor way of storing that information. It should be in this format:

 

$_SESSION["viks_cart_array"][$item_id] = $quantity

 

Then this becomes a VERY simple process. Creating the item_id and quantity as separate sub-keys is problematic.

 

EDIT: Also the code is inefficient. There is a loop of the array that uses $index & $value - but then those aren't used within the loop as they should be and instead the full array path is listed.

Edited by Psycho
Link to comment
Share on other sites

 

The array look like this

Array
(
    [0] => Array
        (
            [item_id] => 1
            [quantity] => 0
        )

    [1] => Array
        (
            [item_id] => 2
            [quantity] => 1
        )

)

Each subarray contains item id and qty

 

 

I tried  this but no success

 

if (isset ($_GET["remove"])) {
$x = $_GET["remove"];


foreach($_SESSION["viks_cart_array"] as $index => $value) {
if ($_SESSION["viks_cart_array"][$index]['item_id'] == $x) {


if ($_SESSION["viks_cart_array"][$index]['quantity'] == 0) {
unset ($_SESSION["viks_cart_array"][$index]);


} else {
$_SESSION["viks_cart_array"][$index]['quantity'] = $q - 1;
}
}
}
};
Edited by arunpatal
Link to comment
Share on other sites

The array should look like this:

Array
(
    [1] => 0
    [2] => 1
)

Where the 1 & 2 as indexes are the item IDs and the 0 & 1 are the quantities.

 

If you set up your array correctly the code to do what you want could look like this [Note: no need to iterate over every item in the array!]:

//remove one quantity from item
if (isset ($_GET["remove"]))
{
    //Set the item ID to reduce
    $itemIdToRemove = intval($_GET["remove"]);
    if(isset($_SESSION["viks_cart_array"][$itemIdToRemove]))
    {
        //Reduce quantity by 1
        $_SESSION["viks_cart_array"][$itemIdToRemove]--;
        //Remove ANY items from cart where quantity is 0
        $_SESSION["viks_cart_array"] = array_filter($_SESSION["viks_cart_array"]);
    }
    header("location:{$_SERVER['PHP_SELF']}");
    exit();
}
Edited by Psycho
Link to comment
Share on other sites

I too am a bit unclear about what you really want vs. code you posted, so this is just a half guess, but perhaps this will work for you:

 

$_SESSION["viks_cart_array"] = array_filter(
  $_SESSION["viks_cart_array"],
  function($elem) {
    return $elem['quantity'];
  }
);
This will give for example:

 

// before
Array
(
    [viks_cart_array] => Array
        (
            [0] => Array
                (
                    [quantity] => 1
                )

            [1] => Array
                (
                    [quantity] => 2
                )

            [2] => Array
                (
                    [quantity] => 0
                )

            [3] => Array
                (
                    [quantity] => 3
                )

            [4] => Array
                (
                    [quantity] => 0
                )

        )

)

// after
Array
(
    [viks_cart_array] => Array
        (
            [0] => Array
                (
                    [quantity] => 1
                )

            [1] => Array
                (
                    [quantity] => 2
                )

            [3] => Array
                (
                    [quantity] => 3
                )

        )

)
Link to comment
Share on other sites

Pyshco array structure is the way to go, as you can immediatly look up the items quantiy using its id as the key to $_SESSION["viks_cart_array"]. Rather then looping over each item one by one checking for items id matches.

 

But working with your current array structure, this will remove the item from the array if the items quantity becomes 0 or less

//remove one quantity from item
if (isset ($_GET["remove"])) {
	$x = $_GET["remove"];

	foreach($_SESSION["viks_cart_array"] as $index => &$item) {
		if ($item['item_id'] == $x) {

			// take 1 away from the qantity			
			$item['quantity'] -= 1;
			
			// if item quantity 0 or less
			if($item['quantity'] <= 0)
				unset($_SESSION["viks_cart_array"][$index]); // remove current item from array

			break;
		}
	}

	header("location:" . $_SERVER["PHP_SELF"]);
	exit;
};
Edited by Ch0cu3r
Link to comment
Share on other sites

  • Solution

 

Pyshco array structure is the way to go, as you can immediatly look up the items quantiy using its id as the key to $_SESSION["viks_cart_array"]. Rather then looping over each item one by one checking for items id matches.

 

But working with your current array structure, this will remove the item from the array if the items quantity becomes 0 or less

//remove one quantity from item
if (isset ($_GET["remove"])) {
	$x = $_GET["remove"];

	foreach($_SESSION["viks_cart_array"] as $index => &$item) {
		if ($item['item_id'] == $x) {

			// take 1 away from the qantity			
			$item['quantity'] -= 1;
			
			// if item quantity 0 or less
			if($item['quantity'] <= 0)
				unset($_SESSION["viks_cart_array"][$index]); // remove current item from array

			break;
		}
	}

	header("location:" . $_SERVER["PHP_SELF"]);
	exit;
};

I got your point....

 

Your code work but i will change my code to make life easy....

Link to comment
Share on other sites

So finally i comeup with this

//remove one quantity from item
if (isset ($_GET["index"])) {
	$index = $_GET["index"]; 

if ($_SESSION["viks_cart_array"][$index]["quantity"] <= 1){
	unset ($_SESSION["viks_cart_array"][$index]); }
	
	else{
		
		$q = $_SESSION["viks_cart_array"][$index]['quantity'];
		$_SESSION["viks_cart_array"][$index]['quantity'] = $q - 1;
		header("location:" . $_SERVER["PHP_SELF"]);
		
		}
};

Code is working fine but please correct me if it can be better :)

 

Thanks to all

Link to comment
Share on other sites

You need to check the quantity after you have taken 1 away.

if (isset ($_GET["index"])) {
    $item_id = $_GET["index"]; 

    // make sure key exists
    if(isset($_SESSION["viks_cart_array"][$item_id ])) {

        // now take one away from quantity
        $_SESSION["viks_cart_array"][$item_id ]['quantity'] -= 1;

        // check quantity if its zero or less
        if ($_SESSION["viks_cart_array"][$item_id]["quantity"] <= 0){
	     unset($_SESSION["viks_cart_array"][$item_id ]); // remove
        }

        header("location:" . $_SERVER["PHP_SELF"]);
        exit;
    } else {
        // item doesn't exist
        // display or log error here
    }
};
Edited by Ch0cu3r
Link to comment
Share on other sites

 

You need to check the quantity after you have taken 1 away.

 

Not with the code he posted. He first checks if the quantity is 1 or less. If so, he removed the item. So, in the else condition, he is guaranteed that the quantity is 2 or greater. Thus, it would never be 0 when reduced by 1. But, on general principal I agree that your version is better. Less branching logic results in cleaner code.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.