0

I tried to get rid of the last comma out of my result from a for loop, but rtrim gets rid of all commas, not only the last one.

This is what I tried

$myCoinsCoinReader = array_keys($myCoins);

for ($i = 0; $i < sizeof($myCoins); $i++) {
    $coinReader = $myCoinsCoinReader[$i] . ',';
    $resultReader = rtrim($coinReader, ",");

    echo $resultReader;
};

The Result of $coinReader is BTC,ETH, The Result of $resultReader is BTCETH (all commas gone)

What can I do to only get rid of the last comma?

Thanks in advance

  • 1
    Possible duplicate of [PHP - How to remove all specific characters at the end of a string?](https://stackoverflow.com/questions/2053830/php-how-to-remove-all-specific-characters-at-the-end-of-a-string) – Sfili_81 May 17 '19 at 14:29
  • 1
    You could just use [implode](https://php.net/manual/en/function.implode.php) on an array in PHP instead of manually attaching commas. – nice_dev May 17 '19 at 14:30
  • Thanks for your answers. Implode worked well. – cmdReligion May 17 '19 at 14:42

3 Answers3

3

Just use implode. For example:

$myCoins = array('BTC' => 45, 'ETH' => 12);
$coinReader = implode(',', array_keys($myCoins));
echo $coinReader;

Output:

BTC,ETH

Demo on 3v4l.org

Nick
  • 123,192
  • 20
  • 49
  • 81
1

I recommend only prepending a comma if it is not the first iteration of the loop:

for ($i=0; $i < sizeof($myCoins); $i++) {
    if ($i > 0) $coinReader .= ',';
    $coinReader = $myCoinsCoinReader[$i];
}

I prefer this approach over right trimming because it lets the for loop build the correct string in one go, rather than having to add a second cleanup step.

Tim Biegeleisen
  • 451,927
  • 24
  • 239
  • 318
1

Simply check which iteration this is. If it is not the last one, then add a comma.

$size = sizeof($myCoins);

$output = "";

for ($i = 0; $i < $size; $i++) {
    $output .= $myCoinsCoinReader[$i];
    if ($size - 1 > $i) {
        $output .= ',';
    }
};

echo $output;

Julius Š.
  • 166
  • 13