How can I add commas to numbers in PHP - php

I would like to know how can I add comma's to numbers. To make my question simple.
I would like to change this:
1210 views
To:
1,210 views
and :
14301
to
14,301
and so on for larger numbers. Is it possible with a php function?

from the php manual http://php.net/manual/en/function.number-format.php
I'm assuming you want the english format.
<?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation with a decimal point and without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
my 2 cents

The Following code is working for me, may be this is helpful to you.
$number = 1234.56;
echo number_format($number, 2, '.', ',');
//1,234.56

$number = 1234.56;
//Vietnam notation(comma for decimal point, dot for thousand separator)
$number_format_vietnam = number_format($number, 2, ',', '.');
//1.234,56

This is a bangladeshi format
First create a function
function numberFormat($number, $decimals=0)
{
// $number = 555;
// $decimals=0;
// $number = 555.000;
// $number = 555.123456;
if (strpos($number,'.')!=null)
{
$decimalNumbers = substr($number, strpos($number,'.'));
$decimalNumbers = substr($decimalNumbers, 1, $decimals);
}
else
{
$decimalNumbers = 0;
for ($i = 2; $i <=$decimals ; $i++)
{
$decimalNumbers = $decimalNumbers.'0';
}
}
// return $decimalNumbers;
$number = (int) $number;
// reverse
$number = strrev($number);
$n = '';
$stringlength = strlen($number);
for ($i = 0; $i < $stringlength; $i++)
{
if ($i%2==0 && $i!=$stringlength-1 && $i>1)
{
$n = $n.$number[$i].',';
}
else
{
$n = $n.$number[$i];
}
}
$number = $n;
// reverse
$number = strrev($number);
($decimals!=0)? $number=$number.'.'.$decimalNumbers : $number ;
return $number;
}
Call the function
* numberFormat(5000000, 2) // 50,00,000.00
* numberFormat(5000000) // 50,00,000

Often, if a number is big enough to have commas in it, you might want to do without any numbers after a decimal point - but if the value you are showing could ever be small, you would want to show those decimal places. Apply number_format conditionally, and you can use it to both add your commas and clip off any irrelevant post-point decimals.
if($measurement1 > 999) {
//Adds commas in thousands and drops anything after the decimal point
$measurement1 = number_format($measurement1);
}
Works well if you are showing a calculated value derived from a real world input.

Give it a try:
function format_my_number() {
$result = number_format(14301,2,',','.');
return $result;
}

Related

php need assistance with regular expression

I want to parse and expand the given strings in PHP.
From
0605052&&-5&-7&-8
0605052&&-4&-7
0605050&&-2&-4&-6&-8
To
0605052, 0605053 ,0605054 ,0605055, 0605057, 0605058
0605052,0605053,0605054,0605057
0605050,0605051,0605052,0605054,0605056,0605058
can someone help me with that? thanks in advance!
Your question is not very clear, but I think you mean a solution like this:
Edited: Now the hole ranges were shown and not only the specified numbers.
<?php
$string = "0605052&&-5&-7&-8";
$test = '/^([0-9]+)\&+/';
preg_match($test, $string, $res);
if (isset($res[1]))
{
$nr = $res[1];
$test = '/\&\-([0-9])/';
preg_match_all($test, $string, $res);
$result[] = $nr;
$nrPart = substr($nr, 0, -1);
$firstPart = substr($nr, -1);
if (isset($res[1]))
{
foreach ($res[1] as &$value)
{
if ($firstPart !== false)
{
for ($i=$firstPart+1; $i<=$value; $i++)
{
$nr = $nrPart . $i;
$result[] = $nr;
}
$firstPart = false;
}
else
{
$nr = $nrPart . $value;
$result[] = $nr;
$firstPart = $value;
}
}
}
var_dump($result);
}
?>
This delivers:
result[0] = "0605052"
result[1] = "0605053"
result[2] = "0605054"
result[3] = "0605055"
result[4] = "0605057"
result[5] = "0605058"
I think a multi step approach is the best thing to do here.
E.g. take this as an example 0605052&&-5&-7&-8:
Split at -. The result will be 0605052&&, 5&, 7&, 8
The first result 0605052&& will help you create your base. Simply substring the numbers by finding first occurence of & and substring to the next to last number. Result will be 060505. You will also need the last number, so get it as well (which is 2 in this case).
Get the remaining ends now, all \d& are simple to get, simply take the first character of the string (or if those can be more than one number, use substring with first occurence of & approach again).
The last number is simple: it is 8.
Now you got all important values. You can generate your result:
The last number from 2., all numbers from 3. and the number from 4. together with your base are the first part. In addition, you need to generate all numbers from the last number of 2. and the first result of 3. in a loop by a step of 1 and append it to your base.
Example Code:
<?php
$str = '0605052&&-5&-7&-8';
$split = explode('-', $str);
$firstAmpBase = strpos($split[0], '&');
$base = substr($split[0], 0, $firstAmpBase - 1);
$firstEnd = substr($split[0], $firstAmpBase - 1, 1);
$ends = [];
$firstSingleNumber = substr($split[1], 0, strpos($split[1], '&'));
for ($i = $firstEnd; $i < $firstSingleNumber; $i++) {
array_push($ends, $i);
}
array_push($ends, $firstSingleNumber);
for ($i = 2; $i < count($split) - 1; $i++) {
array_push($ends, substr($split[$i], 0, strpos($split[$i], '&')));
}
array_push($ends, $split[count($split) - 1]);
foreach ($ends as $end) {
echo $base . $end . '<br>';
}
?>
Output:
0605052
0605053
0605054
0605055
0605057
0605058

How can I add a period after the first three characters and then a ' every 3 characters after?

How can I add a period after the first three characters and then a ' every 3 characters after?
Example
$number = 1100000
Output = 1'100.000
Example2
$number = 560000
Output = 560.000
Example3
$number = 1000256000
Output = 1'000'256.000
I tried number_format but it will add the same symbol (. , ')...thanks!!
$number = 1100000;
$english_format_number = number_format($number, 0, '.', "'");
Output: 1'100'000
$number = 1100000;
$english_format_number = number_format($number, 3, '.', "'");
Output: 1'100'000.000
$number = 1100000;
echo chunk_split($number,1,".");
Thanks!!
You were on the right track with number_format but you have to specify all 4 parameters to achieve the result you are looking for. You also need to divide the number by 1000 to avoid the extra decimal places.
echo number_format($number / 1000, 3, "." , "'");
See: http://php.net/manual/en/function.number-format.php
PHPFiddle: http://phpfiddle.org/main/code/e2c-a6q
I had to do something similar recently, try this function:
function formatMoney($number, $fractional=false) {
if ($fractional) {
$number = sprintf('%.2f', $number);
}
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number) {
$number = $replaced;
} else {
break;
}
}
return $number;
}
edit for your use

Random number that is 15 characters long and positive

I am trying to make random numbers that are exactly 15 characters long and positive using php. I tried rand(100000000000000, 900000000000000) but it still generates negatives and numbers less than 15. Is there another function I am missing that can do this, or should I just use rand(0, 9) 15 times and concatenate the results?
$i = 0;
$tmp = mt_rand(1,9);
do {
$tmp .= mt_rand(0, 9);
} while(++$i < 14);
echo $tmp;
You are using a 32 bit platform. To handle these integers, you need a 64bits platform.
You can do the rand two times and save it as a string, like this:
$num1 = rand(100000,999999);
$num2 = rand(100000,999999);
$num3 = rand(100,999);
$endString = $num1.$num2.$num3;
PS. I like tiggers solution better than mine.
Keep in mind that this will return a string, not an actual integer value.
function randNum($length)
{
$str = mt_rand(1, 9); // first number (0 not allowed)
for ($i = 1; $i < $length; $i++)
$str .= mt_rand(0, 9);
return $str;
}
echo randNum(15);
Here you go.
function moreRand($len) {
$str = mt_rand(1,9);
for($i=0;$i<$len-1;$i++) {
$str .= mt_rand(0, 9);
}
return $str;
}
echo moreRand(15);
Edit: If you want to shave .00045s off your execution time,
function randNum() { return abs(rand(100000000000000, 900000000000000)); }

Generate random 5 characters string

I want to create exact 5 random characters string with least possibility of getting duplicated. What would be the best way to do it? Thanks.
$rand = substr(md5(microtime()),rand(0,26),5);
Would be my best guess--Unless you're looking for special characters, too:
$seed = str_split('abcdefghijklmnopqrstuvwxyz'
.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.'0123456789!##$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];
Example
And, for one based on the clock (fewer collisions since it's incremental):
function incrementalHash($len = 5){
$charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$base = strlen($charset);
$result = '';
$now = explode(' ', microtime())[1];
while ($now >= $base){
$i = $now % $base;
$result = $charset[$i] . $result;
$now /= $base;
}
return substr($result, -5);
}
Note: incremental means easier to guess; If you're using this as a salt or a verification token, don't. A salt (now) of "WCWyb" means 5 seconds from now it's "WCWyg")
If for loops are on short supply, here's what I like to use:
$s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
You can try it simply like this:
$length = 5;
$randomletter = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
more details: http://forum.arnlweb.com/viewtopic.php?f=7&t=25
A speedy way is to use the most volatile characters of the uniqid function.
For example:
$rand = substr(uniqid('', true), -5);
The following should provide the least chance of duplication (you might want to replace mt_rand() with a better random number source e.g. from /dev/*random or from GUIDs):
<?php
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$result = '';
for ($i = 0; $i < 5; $i++)
$result .= $characters[mt_rand(0, 61)];
?>
EDIT:
If you are concerned about security, really, do not use rand() or mt_rand(), and verify that your random data device is actually a device generating random data, not a regular file or something predictable like /dev/zero. mt_rand() considered harmful:
https://spideroak.com/blog/20121205114003-exploit-information-leaks-in-random-numbers-from-python-ruby-and-php
EDIT:
If you have OpenSSL support in PHP, you could use openssl_random_pseudo_bytes():
<?php
$length = 5;
$randomBytes = openssl_random_pseudo_bytes($length);
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters);
$result = '';
for ($i = 0; $i < $length; $i++)
$result .= $characters[ord($randomBytes[$i]) % $charactersLength];
?>
I always use the same function for this, usually to generate passwords. It's easy to use and useful.
function randPass($length, $strength=8) {
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz';
if ($strength >= 1) {
$consonants .= 'BDGHJLMNPQRSTVWXZ';
}
if ($strength >= 2) {
$vowels .= "AEUY";
}
if ($strength >= 4) {
$consonants .= '23456789';
}
if ($strength >= 8) {
$consonants .= '##$%';
}
$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
} else {
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}
It seems like str_shuffle would be a good use for this.
Seed the shuffle with whichever characters you want.
$my_rand_strng = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), -5);
I also did not know how to do this until I thought of using PHP array's. And I am pretty sure this is the simplest way of generating a random string or number with array's. The code:
function randstr ($len=10, $abc="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789") {
$letters = str_split($abc);
$str = "";
for ($i=0; $i<=$len; $i++) {
$str .= $letters[rand(0, count($letters)-1)];
};
return $str;
};
You can use this function like this
randstr(20) // returns a random 20 letter string
// Or like this
randstr(5, abc) // returns a random 5 letter string using the letters "abc"
$str = '';
$str_len = 8;
for($i = 0, $i < $str_len; $i++){
//97 is ascii code for 'a' and 122 is ascii code for z
$str .= chr(rand(97, 122));
}
return $str
Similar to Brad Christie's answer, but using sha1 alrorithm for characters 0-9a-zA-Z and prefixed with a random value :
$str = substr(sha1(mt_rand() . microtime()), mt_rand(0,35), 5);
But if you have set a defined (allowed) characters :
$validChars = array('0','1','2' /*...*/,'?','-','_','a','b','c' /*...*/);
$validCharsCount = count($validChars);
$str = '';
for ($i=0; $i<5; $i++) {
$str .= $validChars[rand(0,$validCharsCount - 1)];
}
** UPDATE **
As Archimedix pointed out, this will not guarantee to return a "least possibility of getting duplicated" as the number of combination is low for the given character range. You will either need to increase the number of characters, or allow extra (special) characters in the string. The first solution would be preferable, I think, in your case.
If it's fine that you'll get only letters A-F, then here's my solution:
str_pad(dechex(mt_rand(0, 0xFFFFF)), 5, '0', STR_PAD_LEFT);
I believe that using hash functions is an overkill for such a simple task as generating a sequence of random hexadecimal digits. dechex + mt_rand will do the same job, but without unnecessary cryptographic work. str_pad guarantees 5-character length of the output string (if the random number is less than 0x10000).
Duplicate probability depends on mt_rand's reliability. Mersenne Twister is known for high-quality randomness, so it should fit the task well.
works fine in PHP (php 5.4.4)
$seed = str_split('abcdefghijklmnopqrstuvwxyz');
$rand = array_rand($seed, 5);
$convert = array_map(function($n){
global $seed;
return $seed[$n];
},$rand);
$var = implode('',$convert);
echo $var;
Live Demo
Source: PHP Function that Generates Random Characters
This simple PHP function worked for me:
function cvf_ps_generate_random_code($length=10) {
$string = '';
// You can define your own characters here.
$characters = "23456789ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $string;
}
Usage:
echo cvf_ps_generate_random_code(5);
Here are my random 5 cents ...
$random=function($a, $b) {
return(
substr(str_shuffle(('\\`)/|#'.
password_hash(mt_rand(0,999999),
PASSWORD_DEFAULT).'!*^&~(')),
$a, $b)
);
};
echo($random(0,5));
PHP's new password_hash() (* >= PHP 5.5) function is doing the job for generation of decently long set of uppercase and lowercase characters and numbers.
Two concat. strings before and after password_hash within $random function are suitable for change.
Paramteres for $random() *($a,$b) are actually substr() parameters. :)
NOTE: this doesn't need to be a function, it can be normal variable as well .. as one nasty singleliner, like this:
$random=(substr(str_shuffle(('\\`)/|#'.password_hash(mt_rand(0,999999), PASSWORD_DEFAULT).'!*^&~(')), 0, 5));
echo($random);
function CaracteresAleatorios( $Tamanno, $Opciones) {
$Opciones = empty($Opciones) ? array(0, 1, 2) : $Opciones;
$Tamanno = empty($Tamanno) ? 16 : $Tamanno;
$Caracteres=array("0123456789","abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ");
$Caracteres= implode("",array_intersect_key($Caracteres, array_flip($Opciones)));
$CantidadCaracteres=strlen($Caracteres)-1;
$CaracteresAleatorios='';
for ($k = 0; $k < $Tamanno; $k++) {
$CaracteresAleatorios.=$Caracteres[rand(0, $CantidadCaracteres)];
}
return $CaracteresAleatorios;
}
I`ve aways use this:
<?php function fRand($len) {
$str = '';
$a = "abcdefghijklmnopqrstuvwxyz0123456789";
$b = str_split($a);
for ($i=1; $i <= $len ; $i++) {
$str .= $b[rand(0,strlen($a)-1)];
}
return $str;
} ?>
When you call it, sets the lenght of string.
<?php echo fRand([LENGHT]); ?>
You can also change the possible characters in the string $a.
Simple one liner which includes special characters:
echo implode("", array_map(function() {return chr(mt_rand(33,126));}, array_fill(0,5,null)));
Basically, it fills an array with length 5 with null values and replaces each value with a random symbol from the ascii-range and as the last, it joins them together t a string.
Use the 2nd array_fill parameter to control the length.
It uses the ASCII Table range of 33 to 126 which includes the following characters:
!"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

php add thousandseperator without adjusting decimal places

I'm looking for a way to use the php number_format function or something similar that will add the thousand seperator but will leave any decimal part of the number intatct without and formatting of this. For example:
39845.25843 => 39,845.25843
347346.8 => 347,346.8
1000000 = > 1,000,000
Thanks
$val = number_format($val, strlen(end(explode('.', $val))));
Edit: if you want to handle integers also the above won't work without adding a case for no decimal
$val = number_format( $val, (strstr($val, '.')) ? strlen(end(explode('.', $val))) : 0 );
I'm with little imagination for variable names, but this will do:
function conv($str) {
$t = explode(".", $str);
$ret = number_format(reset($t), 0);
if (($h = next($t)) !== FALSE)
$ret .= "." . $h;
return $ret;
}
same as above but my twist:
function mod_numberformat($num){
// find & cache decimal part
$pos = strpos($num, '.');
$decimal = $pos !== false ? substr($num, $pos) : '';
// format number & avoid rounding
$number = number_format($num, 9);
// strip new decimal part & concatenate cached part
$number = substr($number, 0, strpos($number, '.'));
$number .= $decimal;
return $number;
}

Categories