0

I have this useragents' array

$userAgents = array ('Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',        //FF4
                   'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20120427 Firefox/15.0a1', //F15
                   'Opera/9.80 (Macintosh; Intel Mac OS X; U; en) Presto/2.2.15 Version/10.00',  //O10
                   'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10', //S5
                   'Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)',                        //IE7
                   'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1)' //IE8
                   'Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; Trident/5.0)' //IE9
                  );

I wanted to get randomly a different user agent, so I used :

$userAgent = $userAgents[array_rand($userAgents)];

How can I do the same random selection but give more weight to, let's say, the 3 first array entries... ?

Alucard
  • 1,814
  • 1
  • 21
  • 33
  • 2
    http://stackoverflow.com/questions/445235/generating-random-results-by-weight-in-php – kevinamadeus May 30 '13 at 08:40
  • @kevinamadeus Thanks Kevinamadeus for the link, but as you see, the first 'naif' suggestion is not a solution, and the other answers includes sums and caluclations for arrays of floats. Im trying to do the random on strings.. – Alucard May 30 '13 at 08:44

2 Answers2

1

You can generate a new array with a weighted result

<?php

$original_array = array(
  // array(weight, string),
  array(1, 'a'),
  array(3, 'b'),
  array(3, 'c'),
  array(2, 'd'),
  array(1, 'e'),
);


$weighted_array = array();

foreach ($original_array as $v) {      
  while ($v[0] > 0) {
    $weighted_array[] = $v[1];    
    $v[0]--;  
  }    
}

Then you can use the $weighted_array with the array_rand function.

var_dump($weighted_array);

/*
array(10) {
  [0]=>      string(1) "a"
  [1]=>      string(1) "b"
  [2]=>      string(1) "b"
  [3]=>      string(1) "b"
  [4]=>      string(1) "c"
  [5]=>      string(1) "c"
  [6]=>      string(1) "c"
  [7]=>      string(1) "d"
  [8]=>      string(1) "d"
  [9]=>      string(1) "e"
}
*/
kevinamadeus
  • 404
  • 2
  • 7
1

I would suggest inserting a simple condition that gives chance to pick fist 3.

$i = rand(0,1); # You can also set more than 1 to get lesser chance.
if($i==1){
    $slice = array_slice($userAgents, 0, 3);
    $userAgent = $userAgents[array_rand($slice)];
}
else
    $userAgent = $userAgents[array_rand($userAgents)];
Goran Lepur
  • 594
  • 1
  • 4
  • 15