Randomizing a PHP Array

I wrote this before it occurred to me to see if MariaDB could randomize the output. It can, with ORDER BY RAND();.

PHP has a shuffle function that can randomize one array, but I have a bunch that need to have the same random order.


// Create an array of numbers
$randomArray = range(0,$numWords-1); 
shuffle($randomArray); 

// Create empty target arrays     
$word = []; $sounds = []; $phrase = []; $sentence = [];

for ( $i = 0; $i < $numWords; $i++ ) {
  // Use the numbers in the random array to swap elements.
  $random = $randomArray[$i];
  $word[$i] = $word_S[$random];
  $sounds[$i] = $sounds_S[$random];
  $phrase[$i] = $phrase_S[$random];
  $sentence[$i] = $sentence_S[$random];
}

Leave a Reply

You must be logged in to post a comment.

Well Golly


Atheism Plus

Buy from Amazon