This code doesn't remove a comma, instead it splits the string into multiple parts using the comma as separator. So you effectively get two strings: One with file.pdf and an empty one (because the part after the comma is nothing), and you are iterating over both using foreach, so you are calling addPDF twice, one time with an empty string (which is probably what causes the error).