Jackson
Jackson

Reputation: 1526

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?

Upvotes: 1

Views: 948

Answers (2)

HarisH Sharma
HarisH Sharma

Reputation: 1267

rand() or mt_rand() generate a random number between given numbers, For array there are some inbuilt function array_rand() and shuffle()

<?php
// array_rand
$input = array("Some", "Many", "More", "A Lot", "All");
$rand_key = array_rand($input);
echo $input[ $rand_key ] . "\n";

.

<?php
// shuffle
$input = array("Some", "Many", "More", "A Lot", "All");
shuffle($input);
echo $input[ 0 ];

You can read more here:

https://www.php.net/manual/en/function.array-rand.php

https://www.php.net/manual/en/function.shuffle.php

Example:

array_rand - https://paiza.io/projects/e9Mo7QCkYqY37nvViWwG0A?language=php

shuffle - https://paiza.io/projects/xVs7O8-tu07JzNQQL0Gu4Q

May be you need this,

Upvotes: 1

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

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.

Upvotes: 2

Related Questions