I've got a string [not an array, it's a load of words stored in one string] and I'd like to put a comma after every word, although not putting one after the last word. I've got;
echo str_replace[' ', ', ', $stilltodo];
but that for some reason adds a space before the comma [and after too but that's right], and also one at the end too. How could I change it to work how I want.
An Example of the 'base' String
French History Maths Physics Spanish Chemistry Biology English DT Maths History DT Spanish English French RS
An Example of the Current Output with the Code above
French , History , Maths , Physics , Spanish , Chemistry , Biology , English , DT , Maths , History , DT , Spanish , English , French , RS ,
Welcome to a short tutorial on how to add commas to numbers in PHP. Need to format and present a “nice-looking” number to the users? The common ways to add commas to numbers in PHP are:
- Use the
number_format[]
function. For example,$num = number_format[12345.678, 2];
- Use regular expressions. For example,
$num = preg_replace["/\B[?=[\d{3}]+[?!\d]]/", ",", 12345.78];
- Manually split the number, add commas, and
combine them back.
$num = explode[".", 12345.78];
$num[0] = implode[",", str_split[strrev[$num[0]], 3]];
$num = strrev[$num[0]] . "." . $num[1];
That covers the quick basics, but read on if you need more concrete examples.
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
QUICK SLIDES
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOAD
Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
All right, let us now get into the various ways and examples of adding commas to numbers in PHP.
METHOD 1] NUMBER FORMAT
1-number-format.php