simple rand() question - php

I need a random 4 digit number
right now im using rand(1000,9999) that always gives me a 4 digit number but i eliminates 0000-0999 as possible results.
how do you pad a random number?
(also this is eventually going to be added to a string do i need to cast the int as a string?)
thanks

In scripting languages like PHP, you don't have to cast in 99% of the cases.
Padding could be done using
sprintf("%04u", rand(0, 9999));
Explanations
the first argument of sprintf specifies the format
% stays for the second, third, forth etc. argument. the first % gets replaced by the second argument, the second % by the third etc.
0 stays for the behaviour of filling with 0 to the left.
4 stays for "At least 4 characters should be printed"
u stays for unsigned integer.

sprintf("%04d", rand(0,9999))
should do what you want

Quick and dirty... how about doing:
rand(10000,19999)
and take the last four digits:
substr(rand(10000, 19999), 1, 4)

str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
Use mt_rand() instead of rand(), it's better.

You can use str_pad() or sprintf() to format your string:
$rand = rand(0, 9999);
$str1 = str_pad($rand, 4, '0', STR_PAD_LEFT);
$str2 = sprintf('%04u', $rand);

Related

Converting this number to human readable form?

I have a database that is ported from an XLS file. My numbers are in this form
3.41002E+13
But the readable form should be : 34100224263318
How can I convert the first form to the second?
Use number_format()
string number_format(float $number, int $decimals = 0, string $dec_point = '.', string $thousands_sep = ',' )
By default, thousands are seperated by ,, that's why you need to pass all four arguments:
number_format(3.41002E+13, 0, ".", "");
34100200000000
As you can see, you have an additional problem: You lose precision - sort of at least: It was never there in the first place.
You need to use number_format, check it out here
You will never be able to get the exact number (e.g. 34100224263318)
"Ex" stands for 10^x, which is used for numbers with a lot of digits as an approximation of the actual number.
number_format is what you can use to get the approximation in a standard human-readable numerical version (Ex is readable too, but anyway).
3.41002E+13 == 3.41002*10^13 == 3.41002 * 100000000000000
It is just a float type. If you want to achieve this you need to use number_format();
number_format(3.41002E+13) == 34100224263318
As phant0m commented if you use
number_format(1.11E-2) == 0,00111
but with integers you will be fine if you want a dot just use
number_format(1.11E-2, 5, '.', '') == 0.00111

Random Number: converting JavaScript to PHP

I have the following line of code in javascript:
(Math.random() + "") * 1000000000000000000
which generates numbers like:
350303159372528000
I tried the same thing in PHP with this:
rand()*1000000000000000000
Which returns:
2.272e+21
I need to use PHP as the number generated will be stored as a SESSION variable and will be used by JavaScript later on.
How do I get PHP to force the number to be an int rather than a float?
EDIT PHP seems to struggle with this.
Would it work if I just generated the rand number in PHP saved it to the SESSION and then done the multiplying by 1000000000000000000 in JavaScript?
How would I go about this?
I'd recommend calling
PHP_INT_MAX
To see if your PHP installation can handle an integar that large. I'm guessing it can't which is why it is knocking it down to scientific notation.
I'd suggest converting your result to an int:
intval(rand()*1000000000000000000)
That said, see Kolink and Jeremy1026 answers for precision issues. If you only need an unique identifier, see Truth's answer.
Update: if you're using strings to represent your numbers, don't want or can't use an arbitrary precision library, and don't stricly need perfecly fair random numbers, you could generate smaller numbers and concat them together:
strval(rand()*999999999 + 1) . strval(rand()*1000000000)
(The +1 is to avoid a leading zero in your result; note also that your number will never have a single digit, but every other number is possible)
For a random number with (exactly) 18 digits, you can also use str_pad in the 2nd part, to fill it with leading zeros:
strval(rand(100000000,999999999)) .
str_pad(strval(rand(0,999999999)), 9, "0", STR_PAD_LEFT)
If you need a unique identifier (which is what it looks like you're trying to do), please use PHP's uniqid() function.
floor() / ceil() / round() / (int) / intval() will convert the number to int.
Also, rand() takes two arguments. If ints are supplied - it will return an integer
And printf() should take care of printing in the format you wish (printf('%d', $int) should do the trick)
In the end I solved the issue like this:
<?php
error_reporting(0);
function RandNumber($e){
for($i=0;$i<$e;$i++){
$rand = $rand . rand(0, 9);
}
return $rand;
}
echo RandNumber(18);
// Outputs a 18 digit random number
?>

number format for calculation

When 10000-100, then result should be 9900.
I tried when I use:-
< ?php
$num1 = number_format(round(10000,1),2);
$num2 = number_format(round(100,1),2);
echo $num1 - $num2;
?>
The above result is -90, that made me realize that the number_format function is not applicable in calculations.
Would there be any way that I can convert a value of number_format (obtained from POST from a previous page) back to numerical value for normal calculation?
To start, the reason is that:
(int) "10,000.00"
resolves to 10 since it stops parsing at the first non-numeric character. Thanks to PHP's weird type system, this is done implicitly when you subtract the strings.
Yes, you can strip out the commas easily:
$unformatted = str_replace(",", "", $formatted);
but it's cleaner to just post the raw numeric value (you can still use number_format for the displayed value).
EDIT: It is good practice to explicitly convert numeric strings (without commas) to float (or int) with either a cast ((int) or (float)) or the function version (intval or floatval).
I don't think you can perform this 10,000.00 -100.00 with the comma in the equation. Just perform the raw arithmetic operation then format the answer.
$num1 = 10000;
$num2 = 100;
echo number_format(round($num1 - $num2,1),2);
This outputs
9,900.00
There is an easier way.
number_format is for fomating output numbers or to round easy numbers.
number_format gives us power to make well fomed rounded numbers, for a better user experience.
For calcualtion and saving Numbers in your MYSQL Database use this.
Save your Numbers in MYSQL always as type DECIMAL not FLOAT. There are lots of bugs if you want to calculate with FLOAT fields.
Than use the english notation.
$number = 1234.56;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', ''); //
// 1234.57
And now you can calculate and save it, without any Bugs.
Always Remember yourself, Saving numbers into $var is always a string.
Yeah, you can deifine type, but it doesn't matter in first case, and its to long to explain here.
For more information about number_format see here -> http://php.net/manual/en/function.number-format.php

Generate integers with leading 0's

I have a project where I have to generate random numbers from 00000 till 99999.
The randomizing isn't where I get stuck, but the fact that it always needs 5 characters is. So when it generates the number 14, I want it as 00014.
What is the best way to achieve this?
sprintf() can do that:
echo sprintf('%05d', 0);
Or use str_pad() - but that's a little bit longer in code:
echo str_pad(0, 5, 0, STR_PAD_LEFT);
str_pad() is able to do what you need the code to be done.
Simply:
$s = str_pad('14', 5, '0', STR_PAD_LEFT);
generate integers with leading 0's
An integer will never have leading 0's.
If you need leading 0's you nedd to convert the integer to an string -> see the answer from thephpdeveloper. This is the right way for writing an number with leading 0's into a database - for example.
If you like to work with that integer (for example for calculations) it's better to leave the integer as an integer (don't change to string) and every time you need to output those numbers -> take the solution from "Stefan Gehrig"
Even substr() can do it:
print substr('0000' . $myRandomNumber, -5);
(Not that I would recommend this. Just wanted to contribute :) )

generate a 5 char long string 0-9 a-z

I need a function in php that can generate a 5 char long string with numbers and a-z
What should I look into?
Other's have already provided you with correct answers, but here's a one-liner, just for the sake of it:
$code = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz'), 0, 5);
str_shuffle randomizes the above string, then substr takes the first 5 letters of that shuffled string. Simple.
As noted in comments for this answer, this function only generates strings that have only unique characters. If one would like to have the strings where even "aaaaa" is possible, here's a little function that allows just that:
function generate($len) {
return substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyz', $len)), 0, $len);
}
echo generate(5);
str_repeat repeats the 0-9a-z string $len times, so every letter has an almost equal possibility for every position. (Read the comments on why only "almost")
For kicks, here's an alternate approach:
//create a random base 36 string
$str = base_convert(rand(), 10, 36);
substr and concatenate as necessary to satisfy length requirements.
This will not give unique characters (e.g., 'aa11a' would be a possible output) -- which may or may not be what the OP wants. Also, the fact that you may need to run the function multiple times to get a string of the requested length means performance may not be spectacular, but if you're only calling this function once or twice, it won't matter.
Here's a more complete implementation:
function randstr($len) {
$currLen = 0;
$value = '';
while($currLen < $len) {
$new = base_convert(rand(), 10, 36);
$value .= $new;
$currLen += strlen($new);
}
//$value may be longer than the requested $len
return substr($value, 0, $len);
}
It's also worth noting that this string will be of less-than-perfect randomness -- the first char of each string output by base_convert will have a bias toward the lower end of the spectrum (as rand() will not completely fill a whole char's worth of bits every time). Ideally, you want a number of bits out of rand that will exactly fill some number of base-36 chars.
Using a source of entropy that gives you more bits than you need for the string in the first place (like /dev/urandom) would resolve this issue. But for most applications, the loss of entropy won't matter enough to justify the overhead of reading /dev/urandom.
Alternately, you could simply throw away the first char of each base_convert() call.
Here’s some example generator:
$length = 5;
$charset = '0123456789abcdefghijklmnopqrstuvwxyz';
$str = '';
while ($length--) {
$str .= $charset[rand() % count($charset)];
}
Do you mean a random string?
If so, simply create a string containing the 36 characters, generate 5 random numbers and create the string based on the character positions (pseudo-code):
string src = "0123456789abcdefghijklmnopqrstuvwxyz"
string dst = ""
for i = 1 to 5:
dst = dst + src[random(len(src))]
If you want 5 unique characters, you do the same thing but with one slight difference.
Generate the first random number in the range 0 through 35, the second in the range 0 through 34 and so on.
Then, as you add the character from the source string to your own string, replace the used character in the source string with the last character in the source string. This will prevent the same character from being selected twice:
string src = "0123456789abcdefghijklmnopqrstuvwxyz"
int srclen = len(src)
string dst = ""
for i = 1 to 5:
idx = randon(len(src))
dst = dst + src[idx]
src[idx] = src[srclen-1]
srclen = srclen - 1
Aside: #Tatu has provided a simple solution using str_shuffle which is a more elegant way of doing that last method (unique characters) but I'm not convinced it's the most efficient way since it's likely to involve a lot of swaps to get a decent shuffle. The method here seems to me to be more likely to be faster.
Keep that in mind if performance is important, but also keep in mind that I haven't tested how good it is - it may be fast enough - it may even blow my solution out of the water :-) As with all performance-related things, measure, don't guess.
http://php.net/manual/en/function.chr.php, in case you dislike hardcoding the alphabet.
Yet another approach, for funsies. Could be shortened - here it's a bit verbose, for readability.
function rand_string($length=5) {
$values = str_split("abcdefghijklmnopqrstuvwxyz0123456789"));
shuffle($values);
$values = array_flip($values);
$string = implode(array_rand($lenght));
return $string;
}

Categories