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 #9043

Various issues in str_shuffle

Details

Submitted2006-10-15 10:49 UTC
Fromjo at durchholz dot org
Assignedaidan
StatusClosed
PackagePHP_Compat
PHP VersionIrrelevant
OSAny
Roadmaps1.6.0a1

Comments

[2006-10-15 10:49 UTC] jo at durchholz dot org

Description:
------------
There are two things wrong with str_shuffle:
1) It shouldn't seed mt_srand. For PHP < 4.2, people should be seeding the random number generators in the main program, and for PHP > 4.2, it's unnecessary (actually bad on a fast machine because it may reseed within the same microsecond).
2) Appending to the result string ($new) causes quadratic behavior. Either append to an array and implode() it on return, or create a string and swap characters inside it.

Here's code that swaps characters (drop-in replacement for the function's body).
Warning: Untested.

$result = (string) $str;
for ($i = strlen ($str) - 1; $i >= 0; $i--) {
// Swap random character from [0..$i] to position [$i].
$j = mt_rand (0, $i);
$tmp = $str [$i];
$str [$i] = $str [$j];
$str [$j] = $tmp;
}
return $result;

[2006-12-14 11:12 UTC] jo at durchholz dot org

Hope you fixed my mistake.
(The loop should be reading and updating $result instead of $str.)