For in random order no repeating numbers

2019-06-07 10:26发布

问题:

Whats the best way to do a random "for" without repeating any number?

for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

I think some ways but are so complicated with a lot amount of code.. There is a standard function to do what im willing?

回答1:

$numbers = range(1,10);
shuffle($numbers);
foreach($numbers as $i) {
    // do stuff
}

That will give you the numbers 1 to 10 with no repetition in a random order.



回答2:

$range = range(1,10);
shuffle($range);
foreach ($range as $i) {
    echo $i;
}


回答3:

Create an array with a range of numbers and then shuffle:

$array = range(1, 10);
shuffle($array);
for ($i=0,$c=count($array); $i<$c; $i++) {
    echo $array[$i] . "\n";
}