PHP Questions Home

Categories

Arrays
Files
Forms
Functions
Images
MySQL
Numbers
Others
Strings
Website


PHP Functions

PHP Functions


More PHP

Top Questions
Ask a Question

How do I add commas easily to a string of numbers?


A common requirement with a string of numbers like this - 123456789 - will be to do something with it, for instance to insert a comma after each number.

More generically, people often ask us "how can I split a string into smaller cunks by inserting a certain character or string at a fixed character interval" - or at least that's what they mean, even if they don't use those exact words.

As ever with PHP there is a function for everything, and one you can use here is the chunk_split function, often used when dealing with emails in PHP.

An example always works best, so here we use this function to insert the ',' after each number:

<?php
$numbers 
implode("",range(1,9));
//or $numbers = 123456789; but where's the fun in that?
print "$numbers"//123456789
//now insert commas
$newnumbers substr(chunk_split($numbers,1,","),0,-1);
print 
"$newnumbers";
//outputs: 1,2,3,4,6,7,8,9
?>


As a simple exercise for the reader, work out why we wrapped the chunk_split inside a substr statement (clue: try running that code without the substring to see why).

So, the chunk_split function takes the string that we are applying the function to, together with the length of each chunk and the and the string to insert every time we reach that number of characters, as arguments.

Try running the above code with chunk_split($numbers,3,".") to get a clearer understanding of how it works.

You will find that this is a really useful little function, which makes it strange that it's perhaps not as well known or used as some other PHP functions.



More strings PHP Questions

How do I count the number of words in my text?
How do I turn a string into an array?
How do I print the " in an echo statement?
How do I extract the values of variables from a string?
What is the difference between ' and "?