phparraysrandom

PHP: How to get value on basis of probability in array?


I have below array

$a = [
 'c1' => '10',
 'c2' => '20',
 'c3' => '10.50',
 'c4' => '19.99'
 'c5' => '19',
 'c6' => '19',
 'c7' => '1.51',
];

c1, c2, c3, c4,... is Value we need on basis of probability 10, 20, 10.50, 19.99,... .

Probability total is going to be 100%

So may be need to use rand() or mt_rand() function, so each time on basis of probability it gives random value from array.

Output can be c2 at 1st time, second time c4, third time may be c2 again

How to achieve this?


Solution

  • you can use rand() along with array_values()

    $rand = rand (0,(count($a)-1));
    
    echo array_values($a)[$rand];
    

    Output: https://3v4l.org/nTPaH AND https://3v4l.org/SSDRR

    Note:- You can use mt_rand() instead of rand() as well.