views:

28

answers:

3

$pieces = explode(",", $userList);

$key=array_search($deleteuser, $pieces);
if(FALSE !== $key)
{
    unset($pieces[$key]);
}
else
    return FALSE;

$userList = implode(",", $pieces);

I'm looking for inputs into how to rework this code to remove an element from a CSV list. The user should exist in this system and it should work fine even if there is one last user in the system (so no commands will exist).

A: 

i dont find the code so bad at all. but you could use for example:

$newUserList = str_replace(",,",",",str_replace($deleteuser,'',$userList));

but it isnt better then yours...

Rufinus
A: 

Here you go:

$arr = explode(',', $userList);
array_pop($arr);
$userList = implode(',', $arr);

But even though this asks your question, your implementation seems to solve "I need to remove a specific user from a CSV", not "I need to remove the last item in a CSV", what is the actual problem?

Andrei Serdeliuc
Why the downvote?
Andrei Serdeliuc
This always removes the first item while the op want to search for a specific item within the list.
VolkerK
This always removes the last item. Question is "Removing last item in a CSV list via PHP's explode / implode"
Andrei Serdeliuc
"it should work fine _even if_ there is one last user in the system"
VolkerK
It does work fine with only one user in the system. try this: `$users = "andrei";$arr = explode(',', $users);print_r($arr);`
Andrei Serdeliuc
+1  A: 

My guess is that you had problems with the last/single item because you're reading the line from a file e.g. via fgets() and you didn't remove the trailing line break from the string. In that case you really should take a look at fgetcsv().
Anyway, to fix your function apply trim() to the input string (or to all array elements after the explode if you like) to remove whitespaces including line breaks.

<?php
echo '--', foo('thisone', 'a,bcd,thisone,e'), "--\n";
echo '--', foo('thisone', 'thisone,e'), "--\n";
echo '--', foo('thisone', "e, thisone\n"), "--\n";
echo '--', foo('thisone', 'thisone'), "--\n";
echo '--', foo('thisone', ''), "--\n";
echo '--', foo('thisone', 'a,thisone,b,thisone,c,thisone'), "--\n";

function foo($deleteuser, $userList) {
  $pieces = array_map('trim', explode(',', $userList));

  foreach( array_keys($pieces, $deleteuser) as $key ) {
    unset($pieces[$key]);
  }
  return  implode(',', $pieces);
}

prints

--a,bcd,e--
--e--
--e--
----
----
--a,b,c--

I've used array_keys instead of array_search() just in case the username can appear more than once in the list.

VolkerK
Hands down winner!
tzmatt7447
... not to demean your effort Volker!
tzmatt7447