1bigbear Posted November 25, 2009 Share Posted November 25, 2009 I am trying to get text from an array, that has 100 words. I want to get two or three random words from the array, what to use to do this? $text= array(one,two, three, things,stuff); Quote Link to comment Share on other sites More sharing options...
waynew Posted November 25, 2009 Share Posted November 25, 2009 I made this: <?php //my example array $my_array = ("Orange","Apple","Berry"); //count how many items are in the array $size_of_array = sizeof($my_array); //-1 because the index of an array starts at 0. $size_of_array = $size_of_array - 1; //number of words you want from the array $num_words = 3; if($size_of_array > ($num_words - 1)){ $num_words = $size_of_array + 1; } //an array that will note down what words we have already got $words_used = array(); //setup loop $counter = 0; while($counter < $num_words){ $rand_index = rand(0,$size_of_array); //get a random index while(in_array($rand_index,$words_used)){ //make sure word not already used $rand_index = rand(0,$size_of_array); //get a random index } echo $my_array[$rand_index]; array_push($words_used,$rand_index); $counter++; } ?> Quote Link to comment Share on other sites More sharing options...
Alex Posted November 25, 2009 Share Posted November 25, 2009 $keys = array_rand($text, 3); echo $text[$keys[0]] . "<br />\n"; echo $text[$keys[1]] . "<br />\n"; echo $text[$keys[2]]; array_rand Quote Link to comment Share on other sites More sharing options...
waynew Posted November 25, 2009 Share Posted November 25, 2009 I just wrote out all of that when there's already a function that does exactly the same thing. Does array_rand() make sure that no two values are given twice? Quote Link to comment Share on other sites More sharing options...
Psycho Posted November 25, 2009 Share Posted November 25, 2009 I just wrote out all of that when there's already a function that does exactly the same thing. Does array_rand() make sure that no two values are given twice? array_unique() Quote Link to comment Share on other sites More sharing options...
1bigbear Posted November 25, 2009 Author Share Posted November 25, 2009 thanks, both scripts work Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.