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); Link to comment https://forums.phpfreaks.com/topic/182951-get-text-from-an-array/ 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++; } ?> Link to comment https://forums.phpfreaks.com/topic/182951-get-text-from-an-array/#findComment-965660 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 Link to comment https://forums.phpfreaks.com/topic/182951-get-text-from-an-array/#findComment-965663 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? Link to comment https://forums.phpfreaks.com/topic/182951-get-text-from-an-array/#findComment-965666 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() Link to comment https://forums.phpfreaks.com/topic/182951-get-text-from-an-array/#findComment-965673 Share on other sites More sharing options...
1bigbear Posted November 25, 2009 Author Share Posted November 25, 2009 thanks, both scripts work Link to comment https://forums.phpfreaks.com/topic/182951-get-text-from-an-array/#findComment-965681 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.