Posted By

digdan on 09/09/08


random array seed shuffle

Versions (?)

Random Seeded Array Shuffle

 / Published in: PHP

Repeatable Fisher Yates Array Shuffle based on given random string. If no seed is provided the current second will be used (not to use as a pure random shuffle... based on microseconds)

  1. function fyshuffle(&$items,$seedstring) {
  2. if (!$seedstring) {
  3. $seedval = time();
  4. } else {
  5. if (is_numeric($seedstring)) {
  6. $seedval = $seedstring;
  7. } else {
  8. for($i=0;$i<=strlen($seedstring);$i++) {
  9. $seedval += ord($seedstring[$i]);
  10. }
  11. }
  13. srand($seedval);
  14. for ($i = count($items) - 1; $i > 0; $i--) {
  15. $j = @rand(0, $i);
  16. $tmp = $items[$i];
  17. $items[$i] = $items[$j];
  18. $items[$j] = $tmp;
  19. }
  20. }

Report this snippet  


RSS Icon Subscribe to comments
Posted By: digdan on May 18, 2009

To understand how this is valuable you need to know how it works. Its a seeded, or what I call a "static" shuffle. Meaning that it will shuffle to the exact same results if the same seed is given. This is tremendous for doing large SEO projects. If you have an array of hundreds of possible title tags that could pertain to the group of articles, then just use the fyshuffle, using the url as the seed, to shuffle your array of possible titles. Then pick the first title. This way the search engines will always get the same title as they did last time, but it won't be the same as the next article in the group.

Posted By: digdan on May 19, 2009

Another good use is random name generators, since the same result will be given every time for each name. Sample script :

You need to login to post a comment.