Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last character from a string [duplicate]

Tags:

php

I have a list of country as an array .. i want this array in following format to later return it via ajax :-

"india","usa","uk" ..

Used following code to get somewhat i was looking for ..

foreach($country_list as $country) {
   $countries .= '"'.$country['label'].'",';
}

problem is it is giving output like "india","usa","uk", ... i.e with trailing comma .

Tried to remove it with

substr_replace($countries, "0", -1);

and

rtrim($countries, ",");

But didnt work ! .. Please help !

like image 399
Prince Singh Avatar asked Jun 21 '26 18:06

Prince Singh


2 Answers

I think that you're missing to assign the variable back after the trim:

$s = '"india","usa","uk",';
$s = rtrim($s, ',');
// prints "india","usa","uk"
print $s;

Demo

Try before buy

like image 195
insertusernamehere Avatar answered Jun 23 '26 10:06

insertusernamehere


try this substr() or mb_substr()

substr($string, 0, -1);
mb_substr($string, 0, -1);

or check this link

like image 39
Haseeb Avatar answered Jun 23 '26 09:06

Haseeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!