0

How i can remove last character dynamically from a php string variable.

$string = '10,20,30,';
echo $string;

Available Output:

10,20,30,

Required Output:

10,20,30
Majbah Habib
  • 4,216
  • 2
  • 32
  • 36

5 Answers5

2

rtrim($string, ","); removes comma at the end of the string.

PHP.net rtrim

trim($string, ","); removes comma at the beginning and end of a string.

PHP.net trim

You can also use implode if you're working with arrays :

PHP.net implode

Example from php.net :

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""

?>
tchartron
  • 450
  • 7
  • 14
  • Right! C'mon you just copied my answer. No hard feelings though. It is fun to see people grasp for points. Go for it! – RST Nov 27 '16 at 10:17
  • No, I thought about implode cause the string looks a lot like it's coming from an array – tchartron Nov 27 '16 at 10:20
2

echo substr($string, 0, strlen($string)-1);

connexo
  • 49,059
  • 13
  • 74
  • 108
0

You could use

rtrim( $string, ',');

But I think your problem lies elsewhere. Seems like you are adding options to this string in a for/while/foreach loop.

Use this instead:

$string = array[];
foreach ($parts as $part) {
  $string[] = $part;
}
$string = implode( $string, ',');
RST
  • 3,798
  • 2
  • 19
  • 32
0

Yes ! I have gotten answer

$string = chop($string,",");

echo $string;

Output

10,20,30

Majbah Habib
  • 4,216
  • 2
  • 32
  • 36
0

If PHP > 7.1 then

$string[-1] = PHP_EOL;

DEMO

nektobit
  • 773
  • 5
  • 11