note 60268 added to function.array-rand
| From: | farooqym at ieee dot org | Date: | Sun, 01 Jan 2006 10:05:48 +0000 |
| Subject: | note 60268 added to function.array-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-101071@lists.php.net to get a copy of this message | ||
Here's an algorithm to make a weighted selection of an item from an array.
Say we have an array $items with keys as items and values as corresponding weights.
For example:
<?php
$items = array(
item1 => 3,
item2 => 4,
item3 => 5,
);
?>
i.e. we want to choose item1 25% of the time, item2 33.3% of the time and item3 41.6% of the time.
Here's a function that works when the weights are positive integers:
<?php
function array_rand_weighted($values) {
$r = mt_rand(1, array_sum($values));
foreach ($values as $item => $weight) {
if ($r <= $weight) return $item;
$r -= $weight;
}
}
?>
Enjoy!
----
Manual Page -- http://www.php.net/manual/en/function.array-rand.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+60268
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+60268&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+60268&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+60268&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+60268&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+60268&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+60268&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+60268&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+60268&report=yes
Search -- http://master.php.net/manage/user-notes.php