Jump to content

[SOLVED] Problems Deleting Array Element


stevesimo

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

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.