Jump to content

Recommended Posts

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

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 ;)

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.