I'm trying to make a PHP program to make a "randomized poem" out of a set of inputed words (from a form). I have the PHP-backend to the point where it'll take the variables, randomly chooose a title, and echo the variables in the order they were put in.

What I want to do is randomize the order. I can't think of a way to do this so that a variable doesn't get chosen twice - in other words, I want to randomize the $w0 - $w14 variable's display order, with no one getting used twice. Below is what I have so far...

Any suggestions?

TIA

<?PHP           
$r = rand(0,14); $wnum = "w".$r; $title = $$wnum; echo "<font size='4'><u>"; echo $title; echo "</font></u>"; echo "<br>&nbsp<br>"; //get the words (15 of them) for ($i = 0; $i < 15; $i++) { $current = "w".$i; if($current == "") { break; } echo $$current; //space echo " "; } ?>

    First off, I strongly recommend to use an array, always simplifies things when they items are similiar 🙂 Just something like $w[0] $w[1] etc. is much better 🙂

    Anyways, I'll look into your script maybe try and get something to go, if I have a successful script I'll attach it 😃

      Something like this seems to work alright:

      function random_word(&$words)
      {
          $r = rand(0,sizeof($words)-1); // Get random index
          $word = $words[$r]; // Get current word
          array_splice($words,$r,1); // Remove this word from array
          return $word; // Return the word
      }
      
      // Set up our words array
      $words = array("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado",
                     "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho",
                     "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky");
      
      // Output words while the words array has entries
      while(sizeof($words)>0)
      {
          echo random_word($words) . "<br>";
      }
      

        You could also look at [man]shuffle[/man] or [man]array_rand[/man]

          Originally posted by Weedpacket
          You could also look at [man]shuffle[/man] or [man]array_rand[/man]

          shuffle() probably is best

            Good call shuffle() does look best.

              Allright. Thanks for your help! I'll try implementing a few of your suggestions, and get back to you guys if it doesn't work.

                I used the Tekime's method with the funtion... Works like a charm! Thanks for your help, guys!

                  Write a Reply...