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



Question:

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

NameA,NameB,NameC  

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:

NameB,NameC  

NOT

,NameB,NameC  

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


Solution:1

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


Solution:2

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


Solution:3

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
Previous
Next Post »