PHP Questions Home | Register | Login
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website
Unanswered

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

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.



Comment on this Question and Answer >>>

ASK A QUESTION

More strings PHP Questions

How do I one-way encrypt a string in PHP?

How do I make the contents of a string lower case?

How do I print text to the screen?

how to compare strings in PHP?

How do we count paragraphs or newlines?



Custom Search