Generate random numbers [duplicate] - php

This question already has answers here:
Generating UNIQUE Random Numbers within a range
(14 answers)
Closed 7 years ago.
I am trying to find a solution in PHP that can generate three random numbers.
At the moment I have this that generates a random number that is different from $randNum;
The numbers need to be different from each other and also different from the variable $randNum
Thank you
$wrong = $randNum;
while ($wrong == $randNum) {
$wrong = rand(0,$max - 1);
}

<?php
$numbers = [];
for($i = 0; $i < 10; $i++){
$number = rand (1,15);
while (in_array($number, $numbers)){
$number = rand (1,15);
}
$numbers[] = $number;
}
echo '<pre>';
print_r($numbers);
echo '</pre>';
This function generates unique 10 random numbers, range from 1-15 you can easy change this script to your needs.

Related

converting number from higher to lower [duplicate]

This question already has answers here:
PHP: How to sort the characters in a string?
(5 answers)
Closed 2 years ago.
we are trying to reorder the number
for example
5695479 to 9976554
48932 to 98432
means all bigger numbers then smaller number.
i was searching for some inbuilt function in php, we found sort function can do with array.
$numbers=array(4,6,2,22,11);
sort($numbers);
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$a=array(4,2,8,6);
usort($a,"my_sort");
i have searched lot but i could not found any inbuilt functions.
There is no specific in-built function for this. However, you can use more than 1 inbuilt function to accomplish your task.
You can convert the integer to string usingstrval.
Now, split the string by each digit to get an array of integers.
Apply rsort() to sort them in descending order.
Implode() them back to get the number you desire.
Snippet:
<?php
$str = strval(5695479);
$nums = str_split($str);
rsort($nums);
echo implode("",$nums);
Another alterantive is to use counting sort for digits. Since digits will always be between 0-9, collect their count and loop from 9 to 0 and get the new number. This method would be faster than the first method if you have the number in string format with huge lengths.
Snippet:
<?php
$num = 48932; // if number is in string format, loop char by char using for loop
$count = [];
while($num > 0){
if(!isset($count[$num % 10])) $count[$num % 10] = 0;
$count[$num % 10]++;
$num = intval($num / 10);
}
$new_num = 0;
for($i = 9; $i >=0; --$i){
if(!isset($count[$i])) continue;
while($count[$i]-- > 0) $new_num = $new_num * 10 + $i; // you would rather concatenate here incase of string.
}
echo $new_num;

Split a number by 13 digits using php [duplicate]

This question already has answers here:
Break long string into pieces php
(5 answers)
Closed 3 years ago.
I want to make a program which splits a long number into pieces of 13 digited number such that I can loop for every 13 digits just using php.
$number = 012345678901230123456789123
Should output
0123456789123
0123456789123
And it should be for any large number having the number of digit multiple of 13.It looks about looping and algorithm but I want to make it as short as possible and I have doubts on how to do it. So I am just asking about the main concept.
The most dynamic solution is probably to use array_functions on the string.
So str_split to make it array then chunk it in size 13 and implode the arrays.
$number = "012345678901230123456789123";
$arr = array_chunk(str_split($number), 13);
foreach($arr as &$val){
$val = implode($val);
}
https://3v4l.org/LsNFt
You can create a function where you can use your string and size as parameter and return an array of strings of the desired length:
function splitString($str, $packetSize) {
$output = [];
$size = strlen($str);
for ($i = 0; $i < $size; $i += $packetSize) {
if ($i + $packetSize < $size) {
$output[]= substr($str, $i, $packetSize);
} else {
$output[]=substr($str, $i);
}
}
return $output;
}

Random string generator PHP [duplicate]

This question already has answers here:
PHP random string generator
(68 answers)
Closed 7 years ago.
I'm trying to create a random string with numbers and letters and I found this function and thought it would be good, but I don't know if it is the correct way to create a true random string or if there is an easier way to do this? Below is what I have:
function randomGen() {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = strlen($chars);
$random;
for ($i = 0; $i < 8; $i++) {
$random = $chars[rand(0, $length - 1)];
}
return $random;
}
You could try using $random = substr(str_shuffle(MD5(microtime())), 0, 8);, which will output the same amount of random characters as you have in your example. I actually prefer this method over most as it doesn't require you to put in the expected characters and even more importantly, it can be done in one line of code!

Incrementing numbers with double digits in php [duplicate]

This question already has answers here:
Formatting a number with leading zeros in PHP [duplicate]
(11 answers)
Closed 7 years ago.
I would like to Increment numbers with double digits if the number is less then 10
This is what i tried so far
$i = 1;
echo $i++;
results is 1,2,3,4,5,6 so on
Then i try adding a condition
$i = 1;
if ($i++<10){
echo "0".$i++;
}else{
echo $i++;
}
Work but skipping the numbers 2,4,6,8 so on.
Can anyone tell me the proper way to do this?
If the condition is only there for the leading zero you can do this much easier with this:
<?php
$i = 10;
printf("%02d", $i++);
?>
if you want prepend something to a string use:
echo str_pad($input, 2, "0", STR_PAD_LEFT); //see detailed information http://php.net/manual/en/function.str-pad.php
On the second fragment of code you are incrementing $i twice, that's why you get only even numbers.
Incrementing a number is one thing, rendering it using a specific format is another thing. Don't mix them.
Keep it simple:
// Increment $i
$i ++;
// Format it for display
if ($i < 10) {
$text = '0'.$i; // Prepend values smaller than 10 with a zero
} else {
$text = $i;
}
// Display it
echo($text);
<?php
$i = 1;
for($i=1;$i<15;){
if($i<10){
echo '0'.$i++."<br>";
}else{
echo $i++."<br>";
}
}
?>

How to make sure that random number will not duplicating? [duplicate]

This question already has answers here:
Generating UNIQUE Random Numbers within a range
(14 answers)
Closed 9 years ago.
I tried to use rand() to make it my unique id in database. But how to make sure that this random number will not be duplicated?
<?php
$num = '';
for ($i = 0; $i < 9; $i++)
$num .= mt_rand(0, 9);
echo '<input name="counter" value="'.$num.'">';
?>
In case you want to insert unique values in the database table (that is how I understood you), it is better to create unique index in the database (which ensures that no duplicate entries are in table for the following column. In case of php, check that duplicate value does not already exist in your array.
<?php
$unique = array();
while( count($unique) < 9)
{
$num = mt_rand(0, 9);
if( isset($unique[$num]) == false )
$unique[$num] = true;
}
print_r($unique);
?>
It's better if you do this way.
First get the range you want with range()
Then you shuffle the array so you can get it in a random order.
Now if you want only 5, you can use array_slice.
$range = range(1, 20);
shuffle($range);
$random = array_slice($range, 0, 5);
print_r($random);
Working example: example

Categories