Page 1 of 1
[SOLVED] array_unique - always unique random values?
Posted: Fri Aug 13, 2004 7:00 pm
by tomfra
Let's say there is an array with 20 different values. I want to pick only 5 random values out of them. This is easy. I want to make sure that there are no duplicates in the results. That's no problem either - array_unique will do that job.
*But*... array_unique simple removes the duplicate value which means there are only 4 values in the result set. What I want it to do is this:
If there is a duplicate, remove it *and* replace it with another unique random value from the remaining 15 values.
How can this be done?
Thanks!
Tomas
Posted: Fri Aug 13, 2004 7:48 pm
by feyd
I'd use [php_man]array_slice[/php_man], that way you can only grab an item from the original list once..

Posted: Fri Aug 13, 2004 7:55 pm
by tomfra
I indeed used array_slice but that returns results with beginning and end that you must choose. I used array_slice for something else (paginating) but for this I would like to choose X numbers of always unique but randomly selected values. I am sure there is a simple solution...
Tomas
Posted: Fri Aug 13, 2004 7:58 pm
by feyd
it's fairly easily done..
Code: Select all
<?php
for($x = 0, $y = min( 5, sizeof( $array ) ); $x < $y; $x++)
$newarray[] = array_slice( $array, mt_rand(0, sizeof( $array ) - 1 ), 1);
?>
something like that...
Posted: Fri Aug 13, 2004 10:11 pm
by tomfra
It doesn't seem to work any better than what I used before because the last set of results has different number of results than the other ones. I probably used wrong example - let's say there are 77 values in the array and I need 5 unique random results in each result set. 20 can be easily divided into 4 result sets but 77 can't if you want to have 5 results in each of them.
That's why I don't think array_slice is a good choice.
Tomas
Posted: Sat Aug 14, 2004 8:41 am
by tomfra
Because the slice problem happened only on the 'last page' which did not have the same number of values as the other results sets, I solved it by creating another slice with the remaining number of values which I took from the beginning of the original array using array_merge.
Thanks for the help!
Tomas