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 05:49 UTC Modified: 2006-12-24 13:59 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  


 [2006-10-15 05: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 01: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 06:12 UTC] jo at durchholz dot org
Hope you fixed my mistake. (The loop should be reading and updating $result instead of $str.)