Good afternoon friends help with the question:

I want to output the answer randomly from an array, but output its index, and not the value?

$ans = array ( 1 => 'да', 2 => 'нет', 3 => 'никогда', 4 => 'очень скоро', 5 => 'забудь', 6 => 'зачем тебе?' ); $vopros = 'Выучу ли я анgлийский'; $random = array_rand($ans); $otvet = $random; echo "Вопрос: {$vopros}<br/>"; echo "ответ: {$otvet}<br/>"; 

The answer is:

Q: Will I learn English?

Answer: 1

  • 3
    $ans[$random] ? - Alexey Shimansky
  • one
    echo "answer: {$ ans [$ random]} <br/>" as a friend suggested above - Wlodzimierz Sitdikowski
  • one
    @WlodzimierzSitdikowski can publish as an answer, only with a more detailed explanation of why ;-) - Alex Shimansky
  • it turned out right, but I don’t understand where the logic is ... please explain - Vika Smirnova
  • one
    the logic is that the array_rand function returns an array key. Therefore, to get the desired value, you need to access the cell of the array by the key returned by the function array_rand. FROM php.net - "Selects one or more random values ​​from an array. Returns the key (or keys) of data of random elements." - Wlodzimierz Sitdikowski

1 answer 1

All right

http://php.net/manual/ru/function.array-rand.php

Returns the key (or keys) of these random elements.

 $otvet = $ans[$random]; 
  • so also true, explain why the variable in square brackets? - Vika Smirnova
  • one
    we take an element of the array $ ans with the key $ random - Dmitry Kozlov
  • one
    @KBMira number is stored in $random . And for arrays, you can access the array element through square brackets ... for example, $ans[1] or $ans['myCustomKey'] .... finally, if $random 1 is allowed in $random , then $ans[$random] will be is equal to $ans[1] ...... that is, instead of a variable, something is substituted ... in general so much can be invested with something $array[$array2[$array3['key'][2]]['something']] ... the truth will be unreadable ... but nonetheless - Alexey Shimansky