Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is PHP selecting the Random Values like that?

So... I was testing something and noticed that when I run this code:

$arr = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890", 1);
print_r(implode(array_rand(array_flip($arr), 16)));

The Output is

Refresh 1: BDFIJKPTVkl12789
Refresh 2: HIJKMQWYdfmorsw3
Refresh 3: FGHMNRVYfhknouw5
Refresh 4: AFIJKRSVeiuwx579
Refresh 5: DJORYZcgijlpqry1
Refresh 6: EISWbhjmoqr45689
Refresh 7: CDEFOTXdhkloqr27
Refresh 8: AEFIKLNORSknx349
Refresh 9: DEFHJMTVZcgpstz0
Refresh 10: CLQTZbefhnpq1279

Why does the output start everytime with 1 to 5 uppercase letters? That "randomness" seems weird to me.

I would like to know why I get this result.

like image 861
Justin99b Avatar asked Dec 22 '18 03:12

Justin99b


People also ask

How do I randomize in PHP?

The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.

How do you randomly choose from a list in PHP?

The array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key.

How do I randomly select an array in PHP?

Method 2: Use array_rand() function to get random value out of an array in PHP. PHP | array_rand() Function: The array_rand() function is an inbuilt function in PHP which is used to fetch a random number of elements from an array. The element is a key and can return one or more than one key.

How do you add random values to an array?

In order to generate random array of integers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.


1 Answers

array_rand (since PHP 5.2.10) no longer shuffles the list of random keys that it generates (you'll notice that your output strings are all in alphabetical order i.e. the characters are in the same order as they are in the input string). If you don't want that behaviour, use shuffle and array_slice instead:

$arr = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890", 1);
shuffle($arr);
echo implode('', array_slice($arr, 0, 16));

Output:

dU54f9wBjZbAKgCP

Demo on 3v4l.org

like image 127
Nick Avatar answered Sep 20 '22 16:09

Nick