technology, the web, movies and randomness.
my blog | photo life | about me
Main » haydur.dot.com » Web Dev »
Unique Random Array Headache

So, I needed to read the contents of a directory, and then pick a set number of unique files, randomly. Now I can get a set of random files, but the keyword here is unique or non-repeating. The quest took me half a day, and really showed how I need to learn PHP a lot more. But what can I do, the damn language has more than 3000 functions (PERL has less than 300!). I found code that can pick one random image from a directory, but it needed moding because I wanted not one, but... lets say 9 randomly picked images. I tried all sorts of loops, stuff like:

for ( (x = getRandomImage()) && i < 10) {
if (!in_array(x,arrayx)) {
arrayx[i] = x;
i++;
}
}

In theory that should work, but for some reason (and I'm too tired to find out) it doesn't. Returns non-repeating randoms alright, but not really 9 of them. Sometimes 8, sometimes 2... like PHP times out and exists the loop after certain number of non-qualifying runs. So anyway, I kept looking around and voila, here's what I found at php.net comments for the rand function:
$list = getImagesList();
$list2=range(1,sizeof($list));
shuffle($list);
$list2=array_slice($list2,0,9);

So finally, I just put this up here so that if you are looking to get a random set of non-repeating (unique) array elements, here's your solution. Good luck.

Posted in Web Dev on April 3, 2006 11:13 PM
Comments
Post a comment...
Thanks for signing in, . Now you can comment. (sign out)







Remember personal info?




:) :D :question: :neutral: :sad: :confused: :mad: :frown: :evil: :exclaim: :eek: :surprised: :rolleyes: :wink: :p

0 Trackbacks:
To trackback this entry, just ping:
http://www.haydur.com/logs/mt-tb.cgi/429
Have a random comment
about this site?
the content? design?
I'm taking orders...