Jump to content

Strip comma at end of loop


JDest

Recommended Posts

This is going to sound like a very beginner question, because it is. I am modifying some free code snippets to fit my use and stuck. It's probably a simple fix.

 

First here is the code. This is printing from a while loop.

<?php print("[". $current_month .",". number_format($remaining_balance, "2", ".", ",") . "],");?>

 

Here is the last remaining items from the loop at it comes to an end:

[343,14,495.86], [344,13,682.26], [345,12,863.91], [346,12,040.79], [347,11,212.87], [348,10,380.12], [349,9,542.52], [350,8,700.02], [351,7,852.61], [352,7,000.26], [353,6,142.94], [354,5,280.62], [355,4,413.26], [356,3,540.85], [357,2,663.34], [358,1,780.72], [359,892.95], [360,0.00], 

 

My question is kind of simple, how do I get it do the comma doesn't print on the last print? I need it to end like this: [359,892.95], [360,0.00]

 

Does that make sense? I don't know if I explained it well. I could really use some help! Thanks so much!

Link to comment
Share on other sites

Hi JDest,

 

The way I would do this is buffer the output into a variable which will then allow you to strip the last , before you print it out as the final step.

 

E.g.

<?php
$buffer = "";
while($current_month<10) {
$buffer .= "[". $current_month .",". number_format($remaining_balance, "2", ".", ",") . "],";
}
print(substr($buffer, 0, -1)); //Remove the last character and print
?>

 

Hope that helps!

Link to comment
Share on other sites

I would first confirm that the last character is comma itself, before trimming it. Just as a precaution that I don't accidentally delete any other character,

 

 

<?php
$buffer = "";
while($current_month<10) {
$buffer .= "[". $current_month .",". number_format($remaining_balance, "2", ".", ",") . "],";
}

if( substr("abcdef", -1) == ',')
print(substr($buffer, 0, -1)); //Remove the last character and print
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.