1

I got this little PHP-snippet:

foreach($parameters as $k => $p) {
    $s .= "$k: '$p',";
}

Okay, now I would like to skip the comma that is added to the $s on the latest item. Is there any elegant method to archive that?

SPQRInc
  • 162
  • 4
  • 23
  • 64

1 Answers1

3

Rather than use logic to skip the comma use a rear trim http://php.net/manual/en/function.rtrim.php

foreach($parameters as $k => $p) {
    $s .= "$k: '$p',";
}
$s = rtrim($s, ",");

This will build the string and then remove the trailing comma for you. It is more efficient than constantly having to check in the loop if this is the last element.

Dan Hastings
  • 3,241
  • 7
  • 34
  • 71