0

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;
2
  • That's because you run your loop for exactly 5 times, but you're not guaranteed to add an item in every iteration. You should rather create a loop that goes on until you have 5 results. Commented Apr 26, 2021 at 9:55
  • Change to a do ... while loop. Commented Apr 26, 2021 at 9:57

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

It seems a bit of an overkill to use nested loops. A do ... while should be sufficient.
0

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.