FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » Random function
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: Random function [message #180551 is a reply to message #180544] Mon, 25 February 2013 22:42 Go to previous messageGo to previous message
Salvatore is currently offline  Salvatore
Messages: 38
Registered: September 2012
Karma:
Member
On 2013-02-25, sonnichjensen(at)gmail(dot)com <sonnichjensen(at)gmail(dot)com> wrote:
> I use the rand function to get 10 items of 1808 current itemes.

If you want ten random items from an array, you could try the following:

<?php
// This is the big array you're pulling something out of.
$lotsOfItems = array( /* ... */ );

// This is the empty array that will eventually contain the ten random
// items.
$tenRandomItems = array();

// Generate a range of numbers between 0 and the number of items minus
// one.
$range = range(0, count($lotsOfItems) - 1);

// Shuffle the array of numbers.
shuffle($range);

while (count($tenRandomItems) < 10) {
$randomOffset = array_shift($range);
$tenRandomItems []= $lotsOfItems[$randomOffset];
}
?>

Using this code, you will never, ever have a duplicate item. However, it
will be far more computationally expensive than using rand() or
mt_rand().

--
Blah blah bleh...
GCS/CM d(-)@>-- s+:- !a C++$ UBL++++$ L+$ W+++$ w M++ Y++ b++
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Request for proofreading
Next Topic: XML error when accessing a certain method of a wsdl service
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Thu Nov 21 21:58:54 GMT 2024

Total time taken to generate the page: 0.04927 seconds