1

Here is my simple code and i'm not able to understand why and how...

$len = 5;   // total number of numbers
$min = 1;  // minimum
$max = 90;  // maximum
$range = array(); // initialize array
foreach (range(0, $len - 1) as $i) {
    while(in_array($num = mt_rand($min, $max), $range));
    //$range[] = $num;
    list($br1, $br2, $br3, $br4, $br5) = $range;
}
print_r($range);

//echo $br1." ".$br2." ".$br3." ".$br4." ".$br5;

Hope in your help...! Thanks!

3
  • What is your expected output? Commented Sep 27, 2017 at 10:19
  • What are you trying to accomplish? Why are you resetting values inside of an array? Commented Sep 27, 2017 at 10:19
  • this script is for getting unique random numbers in a range from 1 to 90 Commented Sep 27, 2017 at 10:24

2 Answers 2

1

Should be written as:

<?php
$len = 5;   // total number of numbers
$min = 1;   // minimum
$max = 90;  // maximum
$range = array(); // initialize array
foreach (range(0, $len - 1) as $i) { // you need to repeat the loop $len times
    // get a new random number in the given range and assign it to $num,
    // do it until the generated number is unique (not present in $range)
    // the loop body is empty, as all the action happens inside its condition
    while(in_array($num = mt_rand($min, $max), $range));

    // append the random number to array
    $range[] = $num;
}
list($br1, $br2, $br3, $br4, $br5) = $range;
echo $br1." ".$br2." ".$br3." ".$br4." ".$br5;

Demo.

The existing version of your code never updates $range variable (the corresponding line is commented out for some reason), that's why it doesn't work.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, now its perfect! Thanks a lot!
1

You need simple modification in your code.Your are assign list in side loop.But which is put out site of loop. And your variable range array are need commented

$len = 5;   // total number of numbers
$min = 1;  // minimum
$max = 90;  // maximum
$range = array(); // initialize array
foreach (range(0, $len - 1) as $i) {
      while(in_array($num = mt_rand($min, $max), $range));
       $range[] = $num;
    }
  list($br1, $br2, $br3, $br4, $br5) = $range;
  print_r($br1);
  print_r($br2);

 //echo $br1." ".$br2." ".$br3." ".$br4." ".$br5;

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.