Posted By

llagerlof on 05/20/19


Tagged

shuffle


Versions (?)

My crappy PHP array shuffle algorithm. Made for fun. Don't trust this.


 / Published in: PHP
 

My crappy PHP array shuffle algorithm. Don't trust this, I did it only for fun. Only works with numeric indexes and it's less randomic with fewer elements.

  1. <?php
  2. /*
  3.   My crappy PHP array shuffle algorithm. Don't trust this, I did it only for fun.
  4.   Only works with numeric indexes and it's less randomic with fewer elements.
  5. */
  6. class Shuffle {
  7. private $unshuffled = array();
  8. private $shuffled = array();
  9.  
  10. public function __construct(array $unshuffled) {
  11. $this->unshuffled = $unshuffled;
  12. }
  13.  
  14. public function shuffle() {
  15. $shuffling = $this->unshuffled;
  16. foreach ($shuffling as $i => $item) {
  17. $insert = rand(0, count($this->unshuffled) - 2);
  18. $last_item = array_pop($shuffling);
  19. $removed_rand = $shuffling[$insert];
  20. $shuffling[$insert] = $last_item;
  21. $shuffling[] = $removed_rand;
  22. }
  23. $this->shuffled = $shuffling;
  24.  
  25. return $this->shuffled;
  26. }
  27. }
  28.  
  29. $Shuffle = new Shuffle(array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'));
  30.  
  31. $shuffled = $Shuffle->shuffle();
  32.  
  33. print_r($shuffled);
  34. ?>

Report this snippet  

You need to login to post a comment.