note 8255 deleted from function.array-rand by sniper
| From: | sniper@php.net | Date: | Fri, 06 Jun 2003 19:47:22 +0000 |
| Subject: | note 8255 deleted from function.array-rand by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-49907@lists.php.net to get a copy of this message | ||
Note Submitter: zak@php.net
----
# If you have not yet been able to upgrade to PHP 4, then here is a function that duplicates
array_rand for PHP3.
function fake_array_rand ($array, $num_req = 1)
{
# Ensure that $num_req has a sane value
$num_req > 0 or $num_req = 1;
$count = count ($array);
for ($n=0; $n < $num_req; ++$n)
{
# Help keep the number generator random :)
$randval
and usleep ("0.$randval");
# Seed the random number generator
# Generate a random number
srand ((double) microtime() * 10000000);
$randval = rand();
# Use the random value to 'pick' an entry from the array
# Count the number of times that the entry is picked
++$index[$randval % $count];
}
# Loop through the array
for ($n = 0; $n < $count; ++$n, next ($array))
{
# When we get to an entry that has been picked
# Put the entry into an array for output
# Don't forget to decrease the counter
while ($index[$n])
{
$out[] = key ($array);
--$index[$n];
}
}
# Return a string if only on random key was asked for
# otherwise return an array
return ($num_req == 1) ? $out[0] : $out ;
}
#
# Trivial Usage Examples
#
# Build a random color triplet for a webpage
$hex_digits = array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
'A','B','C','D','E','F');
$rand_keys = fake_array_rand ($hex_digits, 6);
$color_triplet = $hex_digits[$rand_keys[0]] . $hex_digits[$rand_keys[1]]
. $hex_digits[$rand_keys[2]] . $hex_digits[$rand_keys[3]]
. $hex_digits[$rand_keys[4]] . $hex_digits[$rand_keys[5]];
print "<font color=\"#$color_triplet\">This text may be hard to
read!</font><br /><br />";
# Generate a semi-random sentance
$name = array
('Archie','Betty','Jack','Jane','Jill','John');
$action = array ('down','up','around');
$place = array ('hill','lake','road','tree');
$rand_name = fake_array_rand ($name, 2);
$rand_action = fake_array_rand ($action);
$rand_place = fake_array_rand ($place);
print $name[$rand_name[0]] . ' and ' . $name[$rand_name[1]] . ' went '
. $action[$rand_action] . ' the ' . $place[$rand_place] . '.';
# This function is distributed in the hope that it will be
# useful,but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.