Package home | Report new bug | New search | Development Roadmap Status: Open | Feedback | All | Closed Since Version 1.6.0a3

Bug #9043 Various issues in str_shuffle
Submitted: 2006-10-15 10:49 UTC
From: jo at durchholz dot org Assigned: aidan
Status: Closed Package: PHP_Compat (version 1.5.0)
PHP Version: Irrelevant OS: Any
Roadmaps: 1.6.0a1    
Subscription  
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes. If this is not your bug, you can add a comment by following this link. If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
2006-12-24 18:59 UTC
Package:
Bug Type:
Summary:
From: jo at durchholz dot org
New email:
PHP Version: Package Version: OS:

 

 [2006-10-15 10:49 UTC] jo at durchholz dot org (Joachim Durchholz)
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;

Comments

 [2006-12-14 06:25 UTC] aidan (Aidan Lister)
Thank you very much for the report, sorry we took so long to reply. This fix will be in CVS soon.
 [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.)