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???
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...??
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.
<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.
hmmmm you had 40 unique items or the 40 contained duplicates? cause $yourarray=array_splice($yourarray,$randnum);
should have sliced the last number used?
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..