Unique Random Values I
If you ever needed to get 3 random values off an array in PHP, you'd probably have no problems doing that. But what if your array contained duplicate key and/or value pairs and you still needed to get random yet unique, values?
Sample array with duplicate values
Here's my $sites array filled up with some dummy data to help me explain this problem I faced:
<?php
$sites = array( 'one', 'two', 'two', 'three',
'three', 'three', 'four', 'four', 'four',
'four', 'five', 'five', 'five', 'five',
'five', 'six', 'six', 'six', 'six', 'six',
'six', 'seven', 'seven', 'seven', 'seven',
'seven', 'seven', 'seven', 'eight', 'eight',
'eight', 'eight', 'eight', 'eight', 'eight',
'eight' );
?>
Now all I needed to get done was to somehow get the script to randomly grab 3 unique 'sites' off this array. Easy enough? Yes, quite but it gets complicated in the end! Anyway, here's my first attempt at the code:
Searching an array randomly and return 3 unique values - Method I
Using the popular PHP for loop, here's what I did in the beginning.
<?php
// continued from the code above
for( $i=0; $i<3; $i++ ) // just get 3 diff. sites
{
$r = mt_rand( 0, sizeof($sites)-1 ); // generate random key
// METHOD I
// ========
if( isset($trio) ) # var $trio will hold the lucky 3 sites
{
$c = get_unique( $sites["$r"], $trio ); # function below
if( $c )
{
$trio[] = $c;
}
else
{
--$i;
}
}
else
{
$trio[] = $sites["$r"];
}
// END of METHOD I
// ===============
}
// The function needed for Method I to work
function get_unique( $newsite, $trio )
{
for( $i=0; $i<sizeof($trio); $i++ )
{
if( $newsite === $trio[$i] )
{
return false; // a duplicate site
}
}
return $newsite; // a unique site
}
?>
Now the variable $trio will be filled-up with 3 random and unique values each time you run this script - good... but not quite! :O
Before I tell you what I found out eventually, I want to show you another method I worked out (which does the same thing):
