Go through an Array with a PHP Rand

3

I have 4 buttons which must have options (unique options, that is, they can not be repeated)

The options are in a bd of mysql, and everything works fine except that the options are repeated

The other functions that I have are so that the slogan matches the answers and that.

function rndResponse (){

    GLOBAL $rnd;

    $max = 3; 

    $rnd = rand(0, $max);

    $opciones = array("Correct_Option", "Option_1", "Option_2", "Option_3");

    $response = getResponse($opciones[$rnd]);

    echo $response;

}

and then I call this function from an html using the value of the input, but, I repeat, there are times when the options are repeated. I have four buttons and I call the function in the value of each of them:

<input type="button" value="<?php rndResponse(); ?>"> 
input type="button" value="<?php rndResponse(); ?>"> 
<input type="button" value="<?php rndResponse(); ?>"> 
<input type="button" value="<?php rndResponse(); ?>">

Is there any way this does not happen?

    
asked by Mariano 07.08.2016 в 23:49
source

2 answers

3

The problem is that you are not determining in some way which answer was already printed or not and calling the function each time from the input does not help us much.

An option according to the design of your application would be to determine the order of the answers before showing the buttons:

<?php

    $opciones = ["Correct_Option", "Option_1", "Option_2", "Option_3"];

    // para mezclar el array
    shuffle($opciones);

    foreach ($opciones as $opcion) {
?>

        <input type="button" value="<?php getResponse($opcion); ?>">

<?php } ?>
    
answered by 08.08.2016 в 00:22
1

Instead of executing the PHP code for each of the inputs, it would be advisable to print them in a single execution of the code:

<?php
    // Popular el array
    $opciones = array("Correct_Option", "Option_1", "Option_2", "Option_3");

    // mezclar el array aleatoriamente
    shuffle($opciones);

    // imprimir todos los valores como inputs
    foreach ($opciones as &$valor) {
        echo '<input type="button" value="' . getResponse($valor) . '">';
    }
?>

In this way, all the values of $opciones are printed. If, on the other hand, printing up to a maximum of $max is required, you can change the foreach by

for ($i = 0; $i <= $max; $i++) {
    echo '<input type="button" value="' . getResponse($opciones[$i]) . '">';
}
    
answered by 08.08.2016 в 00:48