The syntax of array_rand reads as follows: array_rand ( array input [, int num_req] ) , where num_req is the number of selectable values.

Then why when setting the parameter num_reg to 1, the random stops working? Those. example number 1:

 $input = array(1,2,3,4,5,6,7,8,9,10,11,12,13); $rnd_key = array_rand($input, 1); // вот тут поставим "1" (в нём-от и загвоздка) $rnd = $input[$rnd_key[0]]; // тут ни чего не получим(!) 

example number 2

 $input = array(1,2,3,4,5,6,7,8,9,10,11,12,13); $rnd_key = array_rand($input, 2); // тут ставим 2 и всё начинает работать. $rnd = $input[$rnd_key[0]]; // тут получим нужное нам, выбранное рандомно, значение. $rnd_2 = $input[$rnd_key[1]]; // тут ещё можем получить и второе значение, которое нам, допустим, и не нужно даже. 

Question: why the first example does not work?

  • 2
    In the first example, check whether the received $ rnd_key really contains the MASSID, and not the scalar value (if you omit the second parameter, it returns the scalar). - Akina
  • @Akina Write this in response - tutankhamun
  • @Akina, that's exactly what I noticed, since I have an array of other numbers, three digits. Now I understand, it means we need to edit the output of the value, on $rnd = $input[$rnd_key]; ! Thank. Now everything in my head with an understanding of the mechanism num_req, fell into place. - I_CaR
  • @tutankhamun Pzhalsta ... - Akina

2 answers 2

In the first example, check whether the received $ rnd_key really contains the MASSID, and not the scalar value (if you omit the second parameter, it returns the scalar).

To always get an array, use qeremy's advice from usernotes to the documentation.

For example for getting random value from assoc arrays

 <?php function array_random_assoc($arr, $num = 1) { $keys = array_keys($arr); shuffle($keys); $r = array(); for ($i = 0; $i < $num; $i++) { $r[$keys[$i]] = $arr[$keys[$i]]; } return $r; } $a = array("a" => "apple", "b" => "banana", "c" => "cherry"); print_r(array_random_assoc($a)); print_r(array_random_assoc($a, 2)); ?> 

Output

 Array ( [c] => cherry ) Array ( [a] => apple [b] => banana ) 

    If you select only one value, the array_rand () function returns the key corresponding to this value.

    Otherwise, it returns an array of keys corresponding to random values.

    Example for one number https://eval.in/754748 and for two https://eval.in/754750