Unique Random Values II
This second method to get 3 random values off an array (with duplicate values) in PHP was actually borne out of a hunch that there's probably a more efficient way to get this done! And I was right...
Searching an array randomly and return 3 unique values - Method II
Using the not-so-popular PHP in_array() function (at least, not to me), here's how I re-wrote the script.
<?php
// replace this with the previous piece of code
for( $i=0; $i<3; $i++ ) // just get 3 diff. sites
{
$r = mt_rand( 0, sizeof($sites)-1 ); // generate random key
// METHOD II
// =========
if( isset($trio) ) # var $trio will hold the lucky 3 sites
{
if( in_array($sites["$r"], $trio) )
{
--$i;
}
else
{
$trio[] = $sites["$r"];
}
}
else
{
$trio[] = $sites["$r"];
}
// END of METHOD II
// ================
}
?>
Method I vs. Method II
While both methods fared well when I was looking to get just 3 random and unique values, the larger this number, the slower Method I gets...
I tried giving either script 1,000 different values in an array and for it to return 999 unique values and here's the result:
Method I |Method II
----------------+-----------------
> 22 seconds! |1.2 - 1.4 seconds
|
It's quite impressive how the speed of Method II (i.e. using the in_array() function) just increases fractionally with so much more data to process!
