Random element from array
Ive currently got the below code which builds an array.
I run this with the following commands: build_playlist_array('A'); build_playlist_array('B'); build_playlist_array('C');
Id now somehow like to get the a random item from each array! Any ideas how i can accomplish this? (I will then be running the command using if's and loops to return 3 random items which are obviously not the same as each other)
$playlist_query = "SELECT * FROM t_playlist WHERE list = '" . $list . "'";
$playlist_result = mysql_query($playlist_query) or die(mysql_error());
while($row = mysql_fetch_array($playlist_result))
$items = $row['songid'];
This is an easy way, but you may have to tweak it for your app.
edit: this solves the problem of how to select songs randomly, but you may also want to store each random selection to a variable and check it each time through the loop to prevent php's rand() function from selecting the same random number twice in a row and playing the same song twice in a row...If your items array is large, back to back selection would be much more rare than if the items array was small...but it still would be cheesy to play the same song twice.
$max = sizeof($items) - 1;
$random = rand(0,$max);
Last edited by hastx; 10-24-2009 at 12:42 PM.
We do precision guesswork
This method does not depend upon the array being sequentially enumerated (e.g. it will work with associative arrays or enumerated arrays with gaps in the indexes).
Slight typo in the above, should be:
Originally Posted by NogDog
Originally Posted by Mindzai
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)