Random array allocation in PHP

I have an array that has values ​​like 1, 5, 6, 9, 11, 45, 56, etc. What I'm trying to do is a random value, maybe 6. Then I want to select a random value, excluding 6 (so there are no doubles). Then a random value, excluding the last two, is all inside the array. Any help? I try to do this without cycles while, but if they are necessary, let it be so.

+3
source share
3 answers

I suggest the following:

# pick a random key in your array
$rand_key = array_rand($your_array);

# extract the corresponding value
$rand_value = $your_array[$rand_key];

# remove the key-value pair from the array
unset($your_array[$rand_key]);

See: array_rand , unset .

+10
source

First shuffle the array, and then use it as a stack:

$a = array(1, 5, 6, 9, 11, 45, 56);
shuffle($a);

// now you can have your picks:
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
...
+7
source
+1

Source: https://habr.com/ru/post/1795296/


All Articles