Reputation: 2207
Im trying to build an function that adds 5 unique numbers that match a certain value.
My snippet below does not always add 5 numbers, and it needs to be 5 unique values.
$random = [];
$val = 22;// this will be random every time
$fields = 100;
$total = 5;
for ($i = 1; $i <= $total; $i++) {
$r = rand(1,$fields);
if(!in_array($r, $random) && $r !== $val){
$random[] = $r;
}
}
return $random;
Upvotes: 0
Views: 57
Reputation: 9130
A single do ... while
loop with a check is all that is required.
Personally, I would use mt_rand()
over rand()
for legacy reasons, but from PHP 7.1.0 onward, rand()
uses the same math as mt_rand()
.
$random = [];
$val = 22; // this will be random every time
$fields = 100;
$total = 5;
do {
$r = mt_rand(1,$fields);
if (($r != $val) && (! in_array($r,$random))){
$random[] = $r;
$total--;
}
} while($total);
var_dump($random);
Sample result:
array(5) {
[0]=>int(56)
[1]=>int(29)
[2]=>int(96)
[3]=>int(92)
[4]=>int(79)
}
Upvotes: 0
Reputation: 144
Create do...while
loop and rand as times as possible if value is already exists in the random array.
$random = [];
$val = 22;// this will be random every time
$fields = 100;
$total = 5;
for ($i = 1; $i <= $total; $i++) {
do {
$r = rand(1, $fields);
} while(in_array($r, $random) || $r === $val);
$random[] = $r;
}
var_dump($random);
Upvotes: 1