Jump to content

Delete Item from Array


Adeus

Recommended Posts

I'm trying to delete an element from my array. I have two dimensions;

 

$_SESSION['cart'] = array(
	array("10", "something1"), 
	array("20", "something2")
	);

 

I am trying to remove one of the element arrays which are inside the session array, in example $_SESSION['cart']['1'] (which would be 20, something2). When I try the following code, it does not remove the array element;

 

if (isset($_POST['remove'])) {
$remove = $_POST['remove'];
array_splice($_SESSION['cart'], $remove, 1);
}

 

Shouldn't this remove the second element in my $_SESSION['cart'] array?

 

I use POST because it is a shopping cart, and to remove an item I have link to the same page with a post (remove=1).

 

Do I need to use unset since the parent array is associative?

 

Thanks for any help.

Link to comment
https://forums.phpfreaks.com/topic/97864-delete-item-from-array/
Share on other sites

Teng,

 

Thanks for the reply but I still have not solved my problem. The example in Reply #2 does not seem to apply, since I am using a key to determine which element to delete. I tried using Barand's suggestion, still to no avail;

 

if (isset($_POST['remove'])) {
$remove = $_POST['remove'];
unset ($_SESSION['cart'][$remove]);
}

 

Any ideas?

<?php session_start();

$_SESSION['cart'] = array("10", "something1","20", "something2");


unset($_SESSION['cart'][0],$_SESSION['cart'][1]);

    
foreach($_SESSION['cart'] as $_SESSION['cart']){
    	
    	
echo " ".$_SESSION['cart']."<br> ";
    
}
    ?>

If the link is in the url it's using the GET method rather than POST.

 

Try $_GET['remove']

 

D'oh!! Silly me... thanks so much.

 

Here is the final working example. Thanks everyone.

 

if (isset($_GET['remove'])) { //check if item is being removed
$remove = $_GET['remove']; //set variable to reflect which element to remove depending on key
unset ($_SESSION['cart'][$remove]); //remove element
$_SESSION['cart'] = array_values($_SESSION['cart']); //sort the array to eliminate gaps in keys
}

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.