Forum Moderators: coopster
Example code:
$the_array = array( "item1", "item2", "item3", "item3" ); //<--Note the extra "item3"
shuffle($the_array);
echo $the_array[0];
Test distribution of results:
<?php
$iterations = 10000;
$the_array = array( "item1", "item2", "item3", "item3" ); //<--Note the extra "item3"
foreach($the_array as $value){
${$value} = 0;
}
for($i=0; $i<=$iterations; $i++){
shuffle($the_array);
${$the_array[0]}++;
}
echo 'Results of '.$iterations.' iterations:<br>';
sort($the_array);
$unique_array = array_unique($the_array);
foreach($unique_array as $key => $value){
echo $value.' '.${$value}.' ('.number_format((${$value}/$iterations),3).'%)<br>';
}
?>
For something more complex (more possibilities and varying probabilities), I don't know the best way to go about it. Hopefully some of the PHP gurus in this forum can chime in. :)
$random_number = rand(0,($array_count-1));
And I was curious to see which was more efficient so I did some benchmarking:
shuffle() method 100,000 iterations:
item1 25,072 (0.251%)
item2 25,055 (0.251%)
item3 49,873 (0.499%)
Completed in 0.64001 seconds.
---
rand() method 100,000 iterations:
item1 24,954 (0.250%)
item2 24,855 (0.249%)
item3 50,191 (0.502%)
Completed in 1.06606 seconds.
---
shuffle() method took 39.96% less time than rand() method.
Benchmarking code:
<?php
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
$iterations = 100000;
$the_array = array( "item1", "item2", "item3", "item3" ); //<--Note the extra "item3"
foreach($the_array as $value){
${$value} = 0;
}
for($i=0; $i<$iterations; $i++){
shuffle($the_array);
${$the_array[0]}++;
}
echo 'shuffle() method
'.number_format($iterations).' iterations:<br>';
sort($the_array);
$unique_array = array_unique($the_array);
foreach($unique_array as $key => $value){
echo $value.' '.number_format(${$value}).' ('.number_format((${$value}/$iterations),3).'%)<br>';
}
$time_end = microtime_float();
$time = round(($time_end - $time_start), 5);
echo 'Completed in '.$time.' seconds.<br>---<br>';
$time_start2 = microtime_float();
$iterations = 100000;
$the_array = array( '0' => "item1", '1' => "item2", '2' => "item3", '3' => "item3" ); //<--Note the extra "item3"
foreach($the_array as $value){
${$value} = 0;
}
for($i=0; $i<$iterations; $i++){
$array_count = count($the_array);
$random_number = rand(0,($array_count-1));
${$the_array[$random_number]}++;
}
echo 'rand() method
'.number_format($iterations).' iterations:<br>';
sort($the_array);
$unique_array = array_unique($the_array);
foreach($unique_array as $key => $value){
echo $value.' '.number_format(${$value}).' ('.number_format((${$value}/$iterations),3).'%)<br>';
}
$time_end2 = microtime_float();
$time2 = round(($time_end2 - $time_start2), 5);
echo 'Completed in '.$time2.' seconds.<br>---<br>';
echo 'shuffle() method took '.number_format(((1-($time/$time2))*100),2).'% less time than rand() method.';
?>