note 74663 deleted from function.substr by nlopess
| From: | nlopess@php.net | Date: | Tue, 01 May 2007 13:43:46 +0000 |
| Subject: | note 74663 deleted from function.substr by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-126052@lists.php.net to get a copy of this message | ||
Note Submitter: chislam4444 at gmail dot com
----
I had a real estate database that had prices with no commas to mark between each hundreds,
thousands, millions, etc. I couldn't find a function that would do this so I decided to make
one, here it is:
<?php
function add_commas($theVar){
$length = strlen($theVar);
$backwards = strrev($theVar);
if(is_numeric(substr($backwards, 0, 4))){
$cut1 = substr($backwards, 0, 3) . ",";
}
if(is_numeric(substr($backwards, 3, 4))){
$cut2 = substr($backwards, 3, 3) . ",";
}
if(is_numeric(substr($backwards, 6, 4))){
$cut3 = substr($backwards, 6, 3) . ",";
}
if(is_numeric(substr($backwards, 9, 4))){
$cut4 = substr($backwards, 9, 3) . ",";
}
$new_backwards = $cut1 . $cut2 . $cut3 . $cut4;
$new_forwards = strrev($new_backwards);
$new_forwards = substr($new_forwards, 1, ($length+2));
return $new_forwards;
}
echo add_commas(30000); // 30,000
echo add_commas(300000); // 300,000
echo add_commas(3000000); // 3,000,000
?>
It's not the most efficient code in the world, but it gets the job done. If you need it go
past 999,999,999 or in other words, into billions and so on, just add
if(is_numeric(substr($backwards, 12, 4))){
$cut5 = substr($backwards, 12, 3) . ",";
}
Then append $cut5 in the $new_backwards, and so on.