How can I remove the last character dynamically from a PHP string variable?
$string = '10,20,30,';
echo $string;
Available output:
10,20,30,
Required output:
10,20,30
How can I remove the last character dynamically from a PHP string variable?
$string = '10,20,30,';
echo $string;
Available output:
10,20,30,
Required output:
10,20,30
 
    
     
    
    rtrim($string, ","); removes a comma at the end of the string.
trim($string, ","); removes a comma at the beginning and end of a string.
You can also use implode if you're working with arrays:
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) ""
?>
 
    
     
    
     
    
     
    
    You could use rtrim():
rtrim($string, ',');
But I think your problem lies elsewhere. It 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, ',');
 
    
     
    
    Yes! I have gotten an answer:
$string = chop($string, ",");
echo $string;
Output
10,20,30
 
    
    