1

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?

4
  • You want random value from $a array everytime? Commented Mar 4, 2020 at 5:06
  • Hi @PrabhjotSinghKainth can't be that case. Sometime it will be same sometime can't Commented Mar 4, 2020 at 5:09
  • 1
    In what units probability is? Looks like percents. In this case the total sum must be 100. Or you can suggest, that sum of this probabilities is 100%. Than you can generate random number from 0 to (10+20+10.50+19.99) and match interval which this number belongs to. [0, 10) - take c1, [10, 30) - take c2, [30, 40.50) - take c3, ... Commented Mar 4, 2020 at 5:17
  • Yes @PavelStepanets It is % and total will be 100% Commented Mar 4, 2020 at 6:12

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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,

Comments

0

I had the same question, yet the checked was not working for my needs: I was searching for a function that rolls a dice on (any) elements in an array, based on their given probabilities. Thats what I came up with:

    /**
     * Dices a value from a given list with percentages.
     *
     * Input be like
     * [
     *  0 => 10.5,
     *  1 => 9.2,
     *  '2.4' => 30,
     *  'foo' => 50.3,
     * ]
     *
     * If sum of $probabilities don't add up to 100, 100 is used to dice against and will maybe hit the fallback.
     * If sum of $probabilities is more than 100, all given $probabilities will be spread accordingly.
     *
     * @param array $probabilities
     * @param mixed $fallback
     * @return mixed
     */
    public static function diceOnArray(array $probabilities, mixed $fallback = null): mixed
    {
        $sum = max(100, array_sum($probabilities));
        $fallback = $fallback ?: array_key_first($probabilities);

        $random = rand(0, $sum);
        foreach ($probabilities as $key => $probability) {
            if ($random > $probability) {
                $random -= $probability;
                continue;
            }
            return $key;
        }
        // hit nothing from the list, use fallback
        return $fallback;
    }

I added the fallback functionality, because I often have collections not summing um to 100 (like 10%, 20% thats it) and therefore I just put $array[0] as the fallback into the function which in a way adds up the first value to what's left to 100%.

Cheers andi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.