Probability poll in PHP

March 20, 2012

I searched for a good way to make a poll in PHP, that made it easy to pick a user by X chance of probability in relation to other users. I did not find any easy and simple solution so I wrote one myself.

class poll {
    private $data = array();
    private $list = array();
    public function add($data, $value){
        $this->data[] = $data;
        for($i=0; $i < $value; $i++){
            list[] = &$this->data[key($this->data)];
    public function get(){
        return $this->list[rand(0, count($this->list)-1)];

You add the items into the poll with specified probability, and then pick one item from the poll based on all the items in it. Example of two users in the poll both having the probability of 50% to be picked:

$poll = new poll();
$poll->add($user1, 50); //or 1
$poll->add($user2, 50); //and 1
$chosen = $poll->get();

There are some flaws and many ways to expand the class (like including the removal of the chosen from the poll – so that you can pick more and not the same twice), but I tried to make the most simple solution of a poll like this.

Hope you like it 🙂