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.