UBB.Dev
Posted By: JoshPet Randomizing an array - 01/16/2004 6:46 AM
If I had an array with a list of say 40 items.

What would be the easiest way to randomize and display a list of 10 of those items???
Posted By: scroungr Re: Randomizing an array - 01/16/2004 7:10 AM
hmm
<?php
$yourarray = array(1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40);

$maxdisplay = 10;

for ($i=0; $i<$maxdisplay; $i++)
{
$maxvalue=count($yourarray);
$randnum = rand(1,$maxvalue);
$yournewarray[]= $yourarray[$randnum];
$yourarray=array_splice($yourarray,$randnum);
}

?>

I guess or something like that to build the new array with the $maxdisplay items from the $yourarray and making sure they are all different...??
Posted By: JoshPet Re: Randomizing an array - 01/16/2004 9:00 AM
Thanks.

That didn't quite do it, as I had duplicates.

Then I did some research and realized I was kinda missing the easy way. Decided just ot shuffle it and output the first X number of keywrds.
Code
<br /><?<br /><br />$keywords = array(<br />"one",<br />"two",<br />"three",<br />"four",<br />"five",<br />"six",<br />"seven"<br />);<br /><br />$maxdisplay = 3;<br /><br />shuffle($keywords);<br /><br />for ($i=0; $i < $maxdisplay; $i++) {<br />	echo "{$keywords[$i]}<br />";<br />}<br />?><br />


But thanks.
Posted By: scroungr Re: Randomizing an array - 01/16/2004 3:39 PM
hmmmm you had 40 unique items or the 40 contained duplicates? cause $yourarray=array_splice($yourarray,$randnum);
should have sliced the last number used?
Posted By: scroungr Re: Randomizing an array - 01/16/2004 3:43 PM
and yeah if they weren't unique you could use
<?php
$numbers = range(1, 20);
srand((float)microtime() * 1000000);
shuffle($numbers);
while (list(, $number) = each($numbers)) {
echo "$number ";
}
?>
but you still have a 1 in 40 chance of getting the same value if the 40 weren't unique..
© UBB.Developers