Re: Randomiser

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Andrew Barnett wrote:
I ended up using an example from the PHP website.

<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);

You're randomizing the whole array which when it gets large, will be noticeable.

If you're using zero based arrays (like above - 'Neo' is item '0', 'Morpheus' is item '1'), I'd suggest something like this:

$input = array (...);

$num_keys = count($input);

$random_keys = array();

$num_to_fetch = 5;
for ($fetched = 0; $fetched < $num_to_fetch; $fetched++) {
  $key = rand(0, $num_keys);
  // if the key has already been picked,
  // decrease "fetched" and try again
  if (in_array($key, $random_keys)) {
    $fetched--;
    continue;
  }
  $random_keys[] = $key;
}

--
Postgresql & php tutorials
http://www.designmagick.com/


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux