stevesimo Posted May 11, 2007 Share Posted May 11, 2007 Hi, I have a string of product IDs in a comma seperated list. I wish to remove one instance of a specified digit from the list. The passed value ID is used to determine which ID to remove. To achieve this I have used the explode function to split the string into an array. I then want to remove one instance of the specified ID using the unset method. Finally I want to reconstruct the list using the implode function. This seems simple enough in theory although I am having problems getting it to work. Here is my code: <?php if ($cart){ $count = 0; //is used to hold status of update $items = explode(',',$cart); //split string using comma as seperator foreach ($items as $item) { //loop through array if ($_GET['id'] == $item && $count == 0) { //if the ID matches and count = 0 remove item from array unset($item); //delete array element $count = 1; //update count so that we only ever get rid of 1 instance of id } //end of if } //end of foreach loop $cart = implode(',',$items); //update } ?> Can anyone offer any advice as to what I am doing wrong as this is starting to frustrate me : ( Thanks Steve (Blackpool) Link to comment https://forums.phpfreaks.com/topic/50938-solved-problems-deleting-array-element/ Share on other sites More sharing options...
redbullmarky Posted May 11, 2007 Share Posted May 11, 2007 doing this: foreach($items as $item) effectively creates a new variable called $item each time. the new var has nothing to do with the original array. what you need is to unset the item from the actual array, so: <?php foreach ($items as $key => $item) { if ($_GET['id'] == $item) { unset($items[$key]); break; } } ?> unrelated: unless there's any reason other than to make sure only one item is deleted, you can avoid using count with 'break' . doesnt work any different, but just a little tidier Link to comment https://forums.phpfreaks.com/topic/50938-solved-problems-deleting-array-element/#findComment-250549 Share on other sites More sharing options...
stevesimo Posted May 11, 2007 Author Share Posted May 11, 2007 Awesome! Thanks for explaining that, I have wasted at least 4 hours trying to work out what I have been doing wrong. Cheers Steve (Blackpool) Link to comment https://forums.phpfreaks.com/topic/50938-solved-problems-deleting-array-element/#findComment-250556 Share on other sites More sharing options...
redbullmarky Posted May 11, 2007 Share Posted May 11, 2007 haha no worries Link to comment https://forums.phpfreaks.com/topic/50938-solved-problems-deleting-array-element/#findComment-250566 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.