PHP Random Numbers
i need to print out numbers 1-100 in a random order. the print statement should be:
echo 'h{'.$num.'}';
what is the shortest cod开发者_StackOverflow社区e to do this?
The easiest way is to use shuffle with an array containing the 100 numbers
e.g.
$sequence = range(1, 100);
shuffle($sequence);
foreach ($sequence as $num) {
echo 'h{'.$num.'}';
}
Also see the range function
EDIT
I thought I might add a little on what shuffle does. Although php.net doesn't explicitly say so, it is likely based on the modern version of the Fisher-Yates shuffle algorithm. For a video demonstration of how it works, see http://www.youtube.com/watch?v=Ckh2DJrP7F4. Also see this excellent flash demonstration
The shuffle algorithm essentially works like this:
- For a given set of elements A1 to AN, and n = N;
- Randomly select an element Ak between A1 and An inclusive
- Swap Ak and An
- Set n = n - 1
- Repeat from step 2
Hope that helps.
See the example for shuffle()
:
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
精彩评论