How to get data from an array and use rand without repeating?

0

I'm doing a quiz, and I saved the answers in an array, I want those answers to appear randomly that does not repeat in the quiz.

I used the following code.

<?php
$times = array('', 'Corinthians', 'Santos', 'Flamengo');
for ($i = 0; $i < 3; $i++) {
$rand = array_rand($times, 2);
?>
<div>
<input type="radio" name="quiz1" value="A">
<label for="questao1-A"><?php echo $times[$rand[1]]; ?></label>
</div>
<?php } ?>
    
asked by anonymous 02.04.2016 / 13:50

1 answer

1

You're using the wrong feature.

shuffle exists for this, see the manual at link .

The shuffle just causes the array to be randomized, so the defined order is ignored, including the indices!

The simplest way to solve what you want is, exactly:

PHP:

<?php

$times = array('', 'Corinthians', 'Santos', 'Flamengo');
shuffle($times);

foreach($times as $time){
?>
<div>
<input type="radio" name="quiz1" value="A">
<label for="questao1-A"><?= $time ?></label>
</div>
<?php } ?>

Test me here!

Result:

<div>
<input type="radio" name="quiz1" value="A">
<label for="questao1-A"></label>
</div>
<div>
<input type="radio" name="quiz1" value="A">
<label for="questao1-A">Flamengo</label>
</div>
<div>
<input type="radio" name="quiz1" value="A">
<label for="questao1-A">Corinthians</label>
</div>
<div>
<input type="radio" name="quiz1" value="A">
<label for="questao1-A">Santos</label>
</div>
  

Note:   Changing to foreach is optional, but for me it improves reading   code and reduces the countless uses of [] next to the parameter, which can   confuse.

    
02.04.2016 / 15:45