How to take data from an array and use Rand without repeating?

Asked

Viewed 2,006 times

1

I’m doing a quiz, and I saved the answers in an array, I want these answers to appear randomly that doesn’t 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 } ?>

1 answer

2


You’re using the wrong resource.

There is the shuffle for this, see in the http://php.net/manual/en/function.shuffle.php.

The shuffle does just make the array in random order, 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!

Upshot:

<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: Shift to the foreach is optional, but for me improves the reading of code and reduces the numerous uses of [] next to the parameter, which can confuse.

  • Because dude, vlwzão, I had found a tutorial on the net, that had to do function and tals, a code of more or less 15 lines, this one saved

Browser other questions tagged

You are not signed in. Login or sign up in order to post.