note 74663 added to function.substr

From: Date: Sun, 22 Apr 2007 22:41:41 +0000
Subject: note 74663 added to function.substr
Groups: php.notes 
Request: Send a blank email to php-notes+get-125771@lists.php.net to get a copy of this message
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. ---- Server IP: 69.39.81.135 Probable Submitter: 68.205.131.219 ---- Manual Page -- http://www.php.net/manual/en/function.substr.php Edit -- https://master.php.net/note/edit/74663 Del: integrated -- https://master.php.net/note/delete/74663/integrated Del: useless -- https://master.php.net/note/delete/74663/useless Del: bad code -- https://master.php.net/note/delete/74663/bad+code Del: spam -- https://master.php.net/note/delete/74663/spam Del: non-english -- https://master.php.net/note/delete/74663/non-english Del: in docs -- https://master.php.net/note/delete/74663/in+docs Del: other reasons-- https://master.php.net/note/delete/74663 Reject -- https://master.php.net/note/reject/74663 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#125771) next »