|
Joined: Nov 2001
Posts: 10,369
I type Like navaho
|
I type Like navaho
Joined: Nov 2001
Posts: 10,369 |
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???
|
|
|
|
Joined: Oct 2003
Posts: 2,305
Old Hand
|
Old Hand
Joined: Oct 2003
Posts: 2,305 |
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...??
|
|
|
|
Joined: Nov 2001
Posts: 10,369
I type Like navaho
|
I type Like navaho
Joined: Nov 2001
Posts: 10,369 |
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.
|
|
|
|
Joined: Oct 2003
Posts: 2,305
Old Hand
|
Old Hand
Joined: Oct 2003
Posts: 2,305 |
hmmmm you had 40 unique items or the 40 contained duplicates? cause $yourarray=array_splice($yourarray,$randnum); should have sliced the last number used?
|
|
|
|
Joined: Oct 2003
Posts: 2,305
Old Hand
|
Old Hand
Joined: Oct 2003
Posts: 2,305 |
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..
|
|
|
Donate to UBBDev today to help aid in Operational, Server and Script Maintenance, and Development costs.
Please also see our parent organization VNC Web Services if you're in the need of a new UBB.threads Install or Upgrade, Site/Server Migrations, or Security and Coding Services.
|
|
Posts: 1,157
Joined: July 2001
|
|
Forums63
Topics37,573
Posts293,925
Members13,849
|
Most Online5,166 Sep 15th, 2019
|
|
Currently Online
Topics Created
Posts Made
Users Online
Birthdays
|
|
|
|