Str_Shuffle and Randomness

str_shuffle and randomness

A better solution would be mt_rand which uses Mersenne Twister which much more better.

As has been pointed out, the str_shuffle method is not equivalent to the code I'm already using and will be less random due to the string's characters remaining the same as the input, only with their order changed. However I'm still curious as to how the str_shuffle function randomizes its input string.

To make the output equal lets just use 0,1 and look at the visual representation of each of the functions

Simple Test Code

header("Content-type: image/png");
$im = imagecreatetruecolor(512, 512) or die("Cannot Initialize new GD image stream");
$white = imagecolorallocate($im, 255, 255, 255);
for($y = 0; $y < 512; $y ++) {
for($x = 0; $x < 512; $x ++) {
if (testMTRand()) { //change each function here
imagesetpixel($im, $x, $y, $white);
}
}
}
imagepng($im);
imagedestroy($im);

function testMTRand() {
return mt_rand(0, 1);
}

function testRand() {
return rand(0, 1);
}

function testShuffle() {
return substr(str_shuffle("01"), 0, 1);
}

Output testRand()

Sample Image

Output testShuffle()

Sample Image

Output testMTRand()

Sample Image

So basically I'd like to know how str_shuffle randomizes the string. Is it using rand() or mt_rand()? I'm using my random string function to generate passwords, so the quality of the randomness matters.

You can see clearly that str_shuffle produces almost same output as rand ...

PHP- How to do str_shuffle make different value?

You should generate your code inside the loop.

//list of possible characters in generated code
$charmap = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";

//note using `:randomcode` instead of the direct variable
$stmt = $pdo->prepare("insert into AGEGroup (AGE) values (:age, :randomcode)");

foreach ($_POST['age'] as $age) {

//create a "random" string that is 8 characters.
//string will never repeat any characters, and can create duplicates
$code = 'NT' . substr(str_shuffle($charmap), -8);

//send variables to query on each loop
$stmt->execute([':age' => $age, ':randomcode' => $code]);
}

As I said in the comments in the code, this method probably has the tendency to create duplicate codes. It will also not contain any duplicate letters/numbers.

php shuffle a pack of cards

Internally, str_shuffle() uses rand() which doesn't produce good quality random numbers as you can see in this answer; if you want a better distribution, you may wish to implement Fisher-Yates yourself and pick a random source of your choice, e.g. mt_rand():

function my_str_shuffle($str)
{
if ($str == '') {
return $str;
}

$n_left = strlen($str);

while (--$n_left) {
$rnd_idx = mt_rand(0, $n_left);
if ($rnd_idx != $n_left) {
$tmp = $str[$n_left];
$str[$n_left] = $str[$rnd_idx];
$str[$rnd_idx] = $tmp;
}
}

return $str;
}

See also my earlier answer on finding a suitable 0/1 randomiser.

Update

Using openssl_random_pseudo_bytes() as your random source:

assert($n_left <= 255);
$random = openssl_random_pseudo_bytes($n_left);

while (--$n_left) {
$rnd_index = round($random[$n_left] / 255 * $n_left);
// ...
}

php str_shuffle does wrong encoding on greek letters

I've looked in the the PHP manual for str_shuffle and found out in the comments that indeed there are problems with some unicode chars.

But there is also a solution there - which I've tested for you, and it works:

<?php

function str_shuffle_unicode($str) {
$tmp = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
shuffle($tmp);
return join("", $tmp);
}

$a = "γκξπψ";
$b = str_shuffle($a);
$c = str_shuffle_unicode($a);

echo $a; // γκξπψ
echo "<br/>str_shuffle: ".$b; // ξ��κ�ψ�
echo "<br/>str_shuffle_unicode: ".$c; // κξγπψ
?>

Random string generator PHP

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!

str_shuffle() equivalent in javascript?

No such function exist, you'll write one yourself. Here's an example:

function shuffle(string) {
var parts = string.split('');
for (var i = parts.length; i > 0;) {
var random = parseInt(Math.random() * i);
var temp = parts[--i];
parts[i] = parts[random];
parts[random] = temp;
}
return parts.join('');
}

alert(shuffle('abcdef'));


Related Topics



Leave a reply



Submit