Reputation: 175
Is there a way to get random numbers from a list of numbers and then put them in order?
For example if I want 4 numbers between 1 and 12 how can I get these numbers in ascending order?
EDIT: I need the numbers to be unique.
Upvotes: 0
Views: 3673
Reputation: 10206
Store the random values in an array and then use PHP's sort function: http://php.net/manual/en/function.sort.php
$numbers = range(1, 12);
shuffle($numbers);
$numbers=array_slice($numbers, 0, 4);
sort($numbers);
Upvotes: 1
Reputation: 5381
Try this up, adding to array, then sorting later on.
foreach and range would be easier to read, so easier to maintain :)
<?php
$b1 = 1;
$b2 = 12;
$nums = array();
foreach(range(1,4) as $i){
$nums[] = rand($b1,$b2);
}
sort($nums);
var_dump($nums);
For more info about sort http://php.net/manual/en/function.sort.php
Upvotes: 0
Reputation: 18595
<?
$y=array();
for($i=0;$i<4;$i++){$y[$i]=mt_rand(1,12);}
sort($y);
?>
Upvotes: 0
Reputation: 1950
$output = array();
for($i=1;$i<=4;$i++){
$output[] = mt_rand(1, 12);
}
sort($output);
Upvotes: 3