0

I want to remove "," from the given string in $code variable but the result is showing "Array" in $code1 instead of balakrishnan. How to rectify the error.

$code="balakrishnan,";
$code1 = explode(',', $code);
1
  • Yes, str_replace or rtrim will help you :)
    – prava
    Commented Jun 2, 2014 at 13:07

3 Answers 3

1

You don't want explode() which splits a string up into an array. You want str_replace() which replaces all occurrences of the search string with the replacement string:

$code1 = str_replace(',', '', $code);

or, in your use case, rtrim() would work, too:

$code1 = rtrim($code, ',');

edit

You do want to use explode(), you just need to access the variables correctly.

$code1 = explode(',',"balakrishnan,kumar,vinoth");
echo $code1[0]; // prints "balakrishnan"
2
  • actually my string like "balakrishnan,kumar,vinoth" how to remove , only Commented Jun 2, 2014 at 13:07
  • Then use str_replace() only
    – John Conde
    Commented Jun 2, 2014 at 13:07
0

If, for some reason you still want to use explode, just do:

echo $code1[0];
0

There is a dozen ways to do this. If you use explode(), also use implode() again.

$code="balakrishnan,";
$code1 = implode('',explode(',', $code));

$code="balakrishnan,";
$code1 = str_replace(',','', $code);

$code="balakrishnan,";
$code1 = substr($code,0,-1);

etc...

I would say, go with my last solution, because in the future you might have other commas in the middle of your string which you might want to keep.

Not the answer you're looking for? Browse other questions tagged or ask your own question.