PEAR is discontinued

This is a static archive preserving historical releases and metadata. No new packages or updates will be published. For updates to existing packages, or to publish new packages, please use Composer and Packagist.

Home » PHP » PHP_Compat » Bug #5078

[patch] Current implementation of str_shuffle sux.

Details

Submitted2005-08-12 16:16 UTC
Frommina86 at tlen dot pl
Assignedaidan
StatusClosed
PackagePHP_Compat
PHP VersionIrrelevant
OSIrrelevant
Roadmaps(Not assigned)

Comments

[2005-08-12 16:16 UTC] mina86 at tlen dot pl

Description:
------------
The current implementation of str_shuffle() is (not to use dirt words) wrong. The bug is since the revision 1.2 of str_shuffle.php file.

Test script:
---------------
<?php
function my_str_shuffle($str) {
$newstr = ''; $strlen = strlen($str); $str = (string) $str;
list($usec, $sec) = explode(' ', microtime());
$seed = (float) $sec + ((float) $usec * 100000);
mt_srand($seed);
for ($i = 0; $strlen > $i; $i++) $newstr .= $str[mt_rand(0, $strlen - 1)];
return $newstr;
}
for ($i = 0; $i<10; ++$i) echo(my_str_shuffle('123') . ' ');
?>

--- correct version --

function str_shuffle($str) {
if (($l=strlen($str=(string)$str))<2) return $str;
list($us, $s) = explode(' ', microtime());
mt_srand((int)$s + (int)((float)$us * 100000));
for ($s=''; $l!==0; $str{$p}=$str{$l}) $s.=$str{$p=mt_rand(0, --$l)};
return $s;
}

Expected result:
----------------
Ten *permutations* of string '123'.

Actual result:
--------------
Definitly not permutations but something like: 312 221 133 331 113 333 212 331 232 111