note 9606 deleted from function.array-rand by sniper
| From: | sniper@php.net | Date: | Fri, 06 Jun 2003 19:47:19 +0000 |
| Subject: | note 9606 deleted from function.array-rand by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-49906@lists.php.net to get a copy of this message | ||
Note Submitter: ssmith@personalcarehmo.com
----
# THE PROBLEM WITH fake_array_rand() IS THAT IT PRODUCES RESULTS THAT CONTAIN
# DUPLICATES. WHAT IF YOU WANT TO RANDOMLY GO THRU EACH ELEMENT
# OF THE ARRAY?
# THEN THIS IS WHAT YOU'RE LOOKING FOR.
# THANKS TO zak@php.net FOR IDEAS FROM THE PREVIOUS CODE SAMPLE THAT
# HELPED ME FIGURE THIS OUT. - scott david smith www.pianocomposer.com
# LIMITATION: $array MUST HAVE AT LEAST TWO ELEMENTS. DUH!
# WARRANTY: Void as soon as you read this. Grin. Hey! It's free.
function fake_array_rand ($array)
{
$num_req = count ($array);
while(count($index) < $num_req)
{
# Help keep the number generator random :)
$randval
and usleep ("0.$randval");
# Seed the random number generator
srand ((double) microtime() * 10000000);
# Generate a random number
$randval = rand();
# Use the random value to 'pick' an entry from the array
# MARK THAT IT'S BEEN USED SO IT CAN'T BE USED AGAIN.
$hi = $randval % $num_req;
if(!isset($index[$hi])){
$index[$hi]=1;
$temp = key($array);
$notused = next($array);
$out[$hi] = $temp;
} # end if
} # end while
# return an array
return ($num_req == 1) ? $out[0] : $out ;
} # end function
# WEIRD SENTENCE GENERATOR.
$name = array
('Sam','Betty','Jack','Jane','Jill','John
Tesh');
$action = array ('looked at','played
with','examined','experimented with');
$place = array ('piano','thing','interesting
item','phaser');
$rand_name = fake_array_rand ($name);
$rand_action = fake_array_rand ($action);
$rand_place = fake_array_rand ($place);
print $name[$rand_name[0]] . ' and ' . $name[$rand_name[1]] . " "
. $action[$rand_action[0]] . ' the ' . $place[$rand_place[0]] . '.';