Advanced SEO
Advanced SEO

Reputation: 387

Randomise list of words in variable

I have variable which is list of words separated by comma like this:

$word_list = "word1, word2, word3, word4, word5";

Word list can contain more or less words than in example above.

How to randomise $word_list to get something like this:

word1, word5, word2, word3, word4

or

word4, word5, word3, word1, word2

Upvotes: 1

Views: 94

Answers (2)

Mason
Mason

Reputation: 1126

You can first explode the string into an array, then shuffle it, and then convert it back to a string.

Something in the lines of this:

$word_array = explode(',', $word_list);
shuffle($word_array);
$shuffeled_word_list = implode(',', $word_array);

Upvotes: 1

BenM
BenM

Reputation: 53198

First, convert it to an array (using explode()), shuffle() the array and then implode() it back to a string:

$word_list = 'word1, word2, word3, word4, word5';
$word_arr  = explode(', ', $word_list);
shuffle( $word_arr );
$rand_list = implode(', ', $word_arr);

Demo

Upvotes: 4

Related Questions