0

I have a string that looks like this

$genres = "pop,rock,jazz,80s";

i was wondering is it possible to then create a string that randomly selects any of those genres above? but removing the comma?

for example it would create

$newgenre = "pop";
shilovk
  • 9,510
  • 16
  • 66
  • 68
  • 1
    didn't you already post something similar ealier? https://stackoverflow.com/questions/47369338/is-it-possible-to-put-an-array-into-a-php-string an you were given a few answers. What's the status of that one? You didn't post a comment under any of them. – Funk Forty Niner Nov 18 '17 at 20:03

4 Answers4

1

You could use something like this:

$genreArray = explode(',', $genres);
$genre = $genreArray[mt_rand(0, count($genreArray))];
Cole
  • 431
  • 2
  • 15
  • This is giving me an error : [18-Nov-2017 19:58:51 UTC] PHP Parse error: syntax error, unexpected ']' in – Jamie Warren Nov 18 '17 at 19:59
  • `mt_rand()` is better than rand. [**why?**](http://php.net/manual/en/function.mt-rand.php) – Martin Nov 19 '17 at 18:51
  • As of 7.1, `rand()` has become an alias for `mt_rand()`, but I've changed it for backwards compatibility. Thanks, @Martin! -CM – Cole Nov 19 '17 at 23:21
1

Alternative Method

Everyone else is using random selection from an array, try this alternative:

$genreArray = explode(',', $genres);
shuffle($genreArray);     //mixes up the array using rand or mt_rand 
$genre = $genreArray[0];  // take first element of shuffled array.
Community
  • 1
  • 1
Martin
  • 20,858
  • 7
  • 60
  • 113
0

You can use the $genreArray = explode(',', $genres) function to put it all into an array. Then you can generate a random index for the array, using

$randomKey = rand(0, count($genreArray))

And then, all you have to do is take the random genre from the array.

$randomGenre = $genreArray[$randomKey];
Tadas
  • 291
  • 1
  • 6
0

You could explode

and get a random value from the array

$genresArray = explode(',',$genres);

$your_values = array_rand ($genresArray,1);

echo $your_values[0];
ScaisEdge
  • 129,293
  • 10
  • 87
  • 97