Tutorial :Fastest way of deleting a value in a comma separated list


I've got a list of names separated by commas (they may contain other characters), or be empty, but generally looking like this:


I need to create a function to delete a name if its present in the list and which restores the comma separated structure.

eg: if NameA is to be deleted, I should end up with:




Similarly for the rest.

This is what I came up with, is there a better solution?

        $pieces = explode(",", $list);            $key=array_search($deleteuser, $pieces);          if(FALSE !== $key)          {              unset($pieces[$key]);          }            $list = implode(",", $pieces);  


You could use the array_splice function to delete from the array. With offset = array_search($deleteuser, $pieces) and length = 1.


That should work pretty well. You may also be interested in PHP's fgetcsv function.
Doc: http://php.net/manual/en/function.fgetcsv.php


You could also try a regular expression like this (maybe it can be optimized):

$search = 'NameB';  $list = 'NameA,NameB,NameC';  $list = preg_match('/(^' . $search . ',)|(,' . $search. ')/', '', $list);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »