Probability poll in PHP

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 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: