Search code examples
phparraysrandomundefined-behavior

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.


Solution

  • 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