3

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 !

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Prince Singh
  • 5,023
  • 5
  • 28
  • 32

9 Answers9

8

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

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
6

try this substr() or mb_substr()

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

or check this link

Community
  • 1
  • 1
Haseeb
  • 2,214
  • 1
  • 22
  • 43
  • see this link. http://stackoverflow.com/questions/5592994/remove-last-character-from-string – Haseeb Aug 16 '13 at 09:45
1

Have you tried using: str_replace(",", " ", $countries);

This function should replace each occurence of a comma with a space.

Matthew Shine
  • 473
  • 4
  • 16
1
if (strlen($b) > 1){
   $b = substr($b,0, -1);
}
user462990
  • 5,472
  • 3
  • 33
  • 35
0

Use implode instead:

$arr = array();
foreach($country_list as $country)
  array_push($arr, $country['label']);
$comma_separated = implode(",", $arr);
Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
0

Try this

$countries = [];
foreach($country_list as $country) {
   $countries[] = $country['label'];
}
$new_array = implode(",", $countries);
Eswara Reddy
  • 1,617
  • 1
  • 18
  • 28
0

Try this

  1. create a variable ($comsep) and initialise it to an empty string.
  2. in the foreach loop concatenate the variable ($comsep) at the start of the string.
  3. add an extra statement in the foreach loop to set the variable ($comsep) to the value "," - after the concatenation statement.

This will put a comma at the start of each appended string except for the first one. The is no longer a trailing comma to deal with so no need to try trimming it off.

0

// Try to use chop() function in php. It helps in removing last character from a string

<?php
    echo '<br>' .$country_name = "'USA','UK','India',";
    echo '<br>' .chop($country_name,",");
    exit;
?>

Output : 'USA','UK','India'

Solomon Suraj
  • 1,162
  • 8
  • 8
-1
foreach($country_list as $country) {
   $countries[] = $country['label'];
}
json_encode($countries); 
Mitali
  • 2,187
  • 1
  • 15
  • 6