Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I easily remove the last comma from an array?

Tags:

arrays

string

php

Let's say I have this:

$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");

foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}

echoes "john-doe,foe-bar,oh-yeah,"

How do I get rid of the last comma?

like image 894
Bastien Avatar asked Sep 24 '10 05:09

Bastien


People also ask

How do you remove a comma at the end of an array?

You can use the join() method in JavaScript to remove commas from an array. The comma delimiter in an array works as the separator.

How do I remove the last comma character from a string?

To remove the last comma from a string, call the replace() method with the following regular expression /,*$/ as the first parameter and an empty string as the second. The replace method will return a new string with the last comma removed. Copied!

How do I remove the last comma in C++?

To easily remove the last comma you can use the '\b' character.

How do you separate an array with a comma?

The comma separated list can be created by using implode() function. The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function.


1 Answers

Alternatively you can use the rtrim function as:

$result = '';
foreach($array as $i=>$k) {
    $result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
like image 67
codaddict Avatar answered Oct 21 '22 02:10

codaddict