How do i remove the 'comma' at the end of a string

hi everyone

i have a string like this “1,2,3,4,5,” or like this “1,2,3,4,5”

i need the end of the string to be a number ( and not the comma). is there a function to dynamically remove the comma if it is at the end of the string.

i am aware that the

    substr($source3 , 0, -2);      

function will remove the last digits of a string. but i need the comma to be removed from the end of the string.

warm regards

Andreea


if(substr($source3, -1) == ',') {
  $source3 = substr($source3, 0, -1);
}

How are you getting the string with the comma on the end in the first place.

A better solution to this problem might be to change the way that the string is created so that the comma doesn’t get put there in the first place.

Here’s a very simple method:


$str = rtrim($str, ',');

hi everyoine

thank you so much for the replies . i really appreciate the advice. i note that felgall commented that a better way would be to avoid having the comma at the end in the first place.

the comma arose because i combined several variables (from a returned form) and then made these vairables into one singl variable ( seperating each of the variable with a comma). i then placed the new varable into the database

example below




		 if(isset($_POST['pre_dis'])) {
				   $pre_dis   =  mysqli_real_escape_string($dbc,trim($_POST['pre_dis']));
			//	  
				 $pre_dis1 = " 1, ";
					}
			  else
				    {
					  $pre_dis  = false;
					 $pre_dis1 = '';
				    }				    
				       	    

		 if(isset($_POST['ADD'])) {
				      $ADD  =  mysqli_real_escape_string($dbc,trim($_POST['ADD']));
			//	      echo "ADD:    $ADD"; 
				 $ADD1 = " 2, ";
					}
			  else
				    {
					  $ADD  = false;
					  $ADD1 = '';
				    }				    		    

				      
		 if(isset($_POST['Auti'])) {
				    $Auti =  mysqli_real_escape_string($dbc,trim($_POST['Auti']));
			//	      echo "Auti:  $Auti"; 
				  $Auti1 = " 3, ";
					}
			  else
				    {
					 $Auti = false;
					  $Auti1 = '';
				    }				    		    


      $qualifiefier =     mysqli_real_escape_string($dbc,trim( "  $pre_dis1  $ADD1    $Auti1  ")



As you can see, i needed to separate these numbers with a comma.

First - why are you placing several values into a single field in the database. With a database each piece of information should be stored in a separate field so as to be able to be processed separately. Combining them in one field removes much of the benefit of using a database.

Also - if you were to create an array to hold the $pre_dis1, $ADD1 and $Auti1 values without the commas and then use implode() to join them together using commas then you’d end up with the same string at the end but without any trailing comma.