Hello there i am making a program which will let me help generate a random string with a specified limit and random strings of *&# but then the combination of *&# should not repeat.
Ex: if I input 3 then the O/P should be
#**
**#
**#
It should generate a random string of length 3 up to 3 rows with different patterns also the pattern should not repeat. I am using the below code but not able to attain it.
$n = 3;
for($i = 0; $i < n; $i++)
{
for($j=0;$j<=$n;j++)
{
echo "*#";
}
echo "<br />";
}
But I am not able to generate the output, where is my logic failing?
If you want to make sure the same pattern doesn't show up more than once you'll have to keep a record of the generated strings. In the most basic form it could look like this:
public function generate() {
$amount = 3; // The amount of strings you want.
$generated_strings = []; // Keep a record of the generated strings.
do {
$random = $this->generateRandomString(); // Generate a random string
if(!in_array($random, $generated_strings)) { // Keep the record if its not already present.
$generated_strings[] = $random;
}
} while(sizeof($generated_strings) !== $amount); // Repeat this process until you have three strings.
print_r($generated_strings);
}
public function generateRandomString($length = 3) {
$characters = '*&#';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Not necessarily the most optimized algorithm but it should work.
I am using a string generator, somewhat random, combining the chars you have provided. The second part is filling the output array with generated strings that are not already present.
<?php
function randomize($n) {
$s = '';
for ($i = 0; $i < $n; $i++) {
$s. = (rand(0, 10) < 5 ? '*' : '#');
}
return $s;
}
$n = 3;
$output = array();
for ($i = 0; $i < $n; $i++) {
$tmp = randomize($n);
while (in_array($tmp, $output)) {
$tmp = randomize($n);
}
$output[] = $tmp;
}
print_r($output);
Visible here
You can use a while loop and array unique to do this.
I first have an array with possible chars.
Then I loop until result array is desired lenght.
I use array unique to remove any duplicates inside the loop.
I use rand(0,2) to "select" a random character from possible characters array.
$arr = ["*", "&", "#"];
$res = array();
$n =7;
While(count($res) != $n){
$temp="";
For($i=0;$i<$n;$i++){
$temp .= $arr[Rand(0,count($arr)-1)];
}
$res[] = $temp;
$res = array_unique($res);
}
Var_dump($res);
https://3v4l.org/Ko4Wd
Updated with out of scope details not clearly specified by OP.
I want to save unique voucher code and mix of characters and numerics and it should be 6 in length. I am using Laravel Framework 5.2
enter code here
$data = $request->all();
unset($data['_token']);
//echo "<pre>"; print_r($data); die;
for ($i=1; $i <=$data['countvoucher']; $i++) {
$voucher = new Voucher;
$voucher->code = "123456";// it should be dynamic and unique
$voucher->percentage = $data['percentage'];
$voucher->usage = $data['usage'];
$voucher->expirydate = $data['expirydate'];
$voucher->save();
}
$voucher->code i want to save in this filed can anyone help me
I am using this function
You may use it like something like bellow
$voucher->code = $this->generateRandomString(6);// it should be dynamic and unique
public function generateRandomString($length = 20) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
private static function generateNumber()
{
$number = Str::random(9);
if (self::where('number', $number)->count() > 0) self::generateNumber();
return $number;
}
You can use Laravel's built-in helper method str_random which generate a more truly "random" alpha-numeric string as:
str_random(6)
The str_random function generates a random string of the specified length. This function uses PHP's random_bytes function.
So your final code will be as:
$voucher->code = str_random(6);
Here is this code
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$code = "";
for ($i = 0; $i < 6; $i++) {
$code .= $chars[mt_rand(0, strlen($chars)-1)];
}
Replace your this line in your code with
$voucher->code = $code;// it should be dynamic and unique
I hope this will work
EDIT
You can try other ways too
$code = strtoupper(uniqid()); // if you dont have any restriction on length of code
For length constraint try this
function generateCouponCode($length = 6) {
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$ret = '';
for($i = 0; $i < $length; ++$i) {
$random = str_shuffle($chars);
$ret .= $random[0];
}
return $ret;
}
use Illuminate\Support\Str;
$random = Str::random(6);
"emPK39"
I have a script which generates 6 character One Time Password (OTP).
Here is the code:-
$seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.'0123456789'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 6) as $k)
$rand .= $seed[$k];
$feedID = $rand;
Now, due to shuffling procedure, currently all 6 can be digits, all 6 can be alphabets.
I want min and max 2 mandatory digits.
How can I do that?
Here's my take on it:
// Create a string of all alpha characters and randomly shuffle them
$alpha = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
// Create a string of all numeric characters and randomly shuffle them
$numeric = str_shuffle('0123456789');
// Grab the 4 first alpha characters + the 2 first numeric characters
$code = substr($alpha, 0, 4) . substr($numeric, 0, 2);
// Shuffle the code to get the alpha and numeric in random positions
$code = str_shuffle($code);
If you want the possibility to have any character more than once, change the two first lines (quick and dirty):
// Let's repeat this string 4 times before shuffle, since we need 4 characters
$alpha = str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4));
// Let's repeat this string 2 times before shuffle, since we need 2 numeric characters
$numeric = str_shuffle(str_repeat('0123456789', 2));
Not saying that this is the best way of doing it, but it's simple, without loops and/or arrays. :)
One more option.
Not saying that this is the best way of doing it, but it's simple, with loops and arrays. ;)
foreach ([4 => range('A', 'Z'), 2 => range(0, 9)] as $n => $chars) {
for ($i=0; $i < $n; $i++) {
$otp[] = $chars[array_rand($chars)];
}
}
shuffle($otp);
$otp = implode('', $otp);
$seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
$seed2= str_split('0123456789');
$rand = [];
for($i=mt_rand(1,2);$i<=2;$i++){
shuffle($seed2);
$rand[]=$seed2[0];
}
while(count($rand)!=6){
shuffle($seed);
$rand[]=$seed[0];
}
shuffle($rand);
print $feedID = implode('',$rand);
you can use random() also to genarate the string with num + letters.LINK
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Hope this help you
function generateRandomString($length = 10,$char_len=4,$numbre_len=2) {
$characters = '0123456789';
$characters2='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$charactersLength2 = strlen($characters);
$randomString = '';
for ($i = 0; $i <$char_len ; $i++) {
$randomString .= $characters2[rand(0, $charactersLength2 - 1)];
}
for ($i = 0; $i <$numbre_len ; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$shuffled = str_shuffle($randomString);
return $shuffled;
}
$length=7;
$char_len=6;
$numbre_len=1;
echo generateRandomString($length,$char_len,$numbre_len);
This function may help to generate dynamic random otp which you want.
I actually got this script from here... but it is not quite what I needed...
<?php
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
// Echo the random string.
// Optionally, you can give it a desired string length.
<?php echo generateRandomString(); ?>
?>
basically, I wanted this small php script to generate thousands of lines (~3000)...
in this format:
mytext/(the_random_string_here)
mytext/(the_random_string_here)
mytext/(the_random_string_here)
mytext/(the_random_string_here)
mytext/(the_random_string_here)
up to the very end (~3000 lines) with each line have a random string...
you can use a for loop to generate it 3000 times
for($i = 0; $i < 3000; $i++){
echo 'mytext/'.generateRandomString().'<br>';
}
The answer was inside your code snippet that you provided
If the number of lines is known, a for loop is a good choice. There is a nice example of such a loop right there in the generateRandomString function.
You could do something like this:
for ($i = 0; $i < 3000; $i++) {
echo "mytext/(" . generateRandomString() . ")<br>\n";
}
How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?
First make a string with all your possible characters:
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
You could also use range() to do this more quickly.
Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string:
$string = '';
$max = strlen($characters) - 1;
for ($i = 0; $i < $random_string_length; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
$random_string_length is the length of the random string.
I like this function for the job
function randomKey($length) {
$pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));
for($i=0; $i < $length; $i++) {
$key .= $pool[mt_rand(0, count($pool) - 1)];
}
return $key;
}
echo randomKey(20);
Generate cryptographically strong, random (potentially) 8-character string using the openssl_random_pseudo_bytes function:
echo bin2hex(openssl_random_pseudo_bytes(4));
Procedural way:
function randomString(int $length): string
{
return bin2hex(openssl_random_pseudo_bytes($length));
}
Update:
PHP7 introduced the random_x() functions which should be even better. If you come from PHP 5.X, use excellent paragonie/random_compat library which is a polyfill for random_bytes() and random_int() from PHP 7.
function randomString($length)
{
return bin2hex(random_bytes($length));
}
One line solution:
echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );
You can change the substr parameter in order to set a different length for your string.
Use the ASCII table to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.
I find that this method is nicer compared to the method described where the range of characters is specifically defined within another string.
// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end = 122;
$random_string = "";
$random_string_length = 10;
for ($i = 0; $i < $random_string_length; $i++) {
$ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
// finds the character represented by $ascii_no and adds it to the random string
// study **chr** function for a better understanding
$random_string .= chr( $ascii_no );
}
echo $random_string;
See More:
chr function
mt_rand function
I know it's an old post but I'd like to contribute with a class I've created based on Jeremy Ruten's answer and improved with suggestions in comments:
class RandomString
{
private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
private static $string;
private static $length = 8; //default random string length
public static function generate($length = null)
{
if($length){
self::$length = $length;
}
$characters_length = strlen(self::$characters) - 1;
for ($i = 0; $i < self::$length; $i++) {
self::$string .= self::$characters[mt_rand(0, $characters_length)];
}
return self::$string;
}
}
Simple guys .... but remember each byte is random between 0 and 255 which for a random string will be fine. Also remember you'll have two characters to represent each byte.
$str = bin2hex(random_bytes(32)); // 64 character string returned
Maybe I missed something here, but here's a way using the uniqid() function.
I have made the following quick function just to play around with the range() function. It just might help someone sometime.
Function pseudostring($length = 50) {
// Generate arrays with characters and numbers
$lowerAlpha = range('a', 'z');
$upperAlpha = range('A', 'Z');
$numeric = range('0', '9');
// Merge the arrays
$workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha));
$returnString = "";
// Add random characters from the created array to a string
for ($i = 0; $i < $length; $i++) {
$character = $workArray[rand(0, 61)];
$returnString .= $character;
}
return $returnString;
}
You can use the following code. It is similar to existing functions except that you can force special character count:
function random_string() {
// 8 characters: 7 lower-case alphabets and 1 digit
$character_sets = [
["count" => 7, "characters" => "abcdefghijklmnopqrstuvwxyz"],
["count" => 1, "characters" => "0123456789"]
];
$temp_array = array();
foreach ($character_sets as $character_set) {
for ($i = 0; $i < $character_set["count"]; $i++) {
$random = random_int(0, strlen($character_set["characters"]) - 1);
$temp_array[] = $character_set["characters"][$random];
}
}
shuffle($temp_array);
return implode("", $temp_array);
}
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
echo generateRandomString();
If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:
substr( sha1( time() ), 0, 15 )
time() gives you the current time in seconds since epoch, sha1() encrypts it to a string of 0-9a-f, and substr() lets you choose a length. You don't have to start at character 0, and whatever the difference is between the two numbers will be the length of the string.
First list the desired characters
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
Use the str_shuffle($string) function. This function will provide you a randomly shuffled string.
$alpha=substr(str_shuffle($chars), 0, 50);
50 is the Length of string.
This is something I use:
$cryptoStrong = true; // can be false
$length = 16; // Any length you want
$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
$randomString = bin2hex($bytes);
You can see the Docs for openssl_random_pseudo_bytes here, and the Docs for bin2hex here
Jeremy's answer is great. If, like me, you're unsure of how to implement range(), you can see my version using range().
<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$string = "";
for($i = 0; $i < 6; $i++) {
$string .= $character_array[rand(0, (count($character_array) - 1))];
}
echo $string;
?>
This does the exact same thing as Jeremy's but uses merged arrays where he uses a string, and uses count() where he uses strlen().
1 line:
$FROM = 0; $TO = 'zzzz';
$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);
echo $code;
The modern way to do that with type hint / rand_int for real randomeness
function random_string(int $size): string
{
$characters = array_merge(
range(0, 9),
range('A', 'Z')
);
$string = '';
$max = count($characters) - 1;
for ($i = 0; $i < $size; $i++) {
$string .= $characters[random_int(0, $max)];
}
return $string;
}
public function randomString($length = 8)
{
$characters = implode([
'ABCDEFGHIJKLMNOPORRQSTUWVXYZ',
'abcdefghijklmnoprqstuwvxyz',
'0123456789',
//'!##$%^&*?'
]);
$charactersLength = strlen($characters) - 1;
$string = '';
while ($length) {
$string .= $characters[mt_rand(0, $charactersLength)];
--$length;
}
return $string;
}